ParseDeclCXX.cpp revision 961743326fd18776f897bf4461345dba680ef637
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 "ExtensionRAIIObject.h" 20using namespace clang; 21 22/// ParseNamespace - We know that the current token is a namespace keyword. This 23/// may either be a top level namespace or a block-level namespace alias. 24/// 25/// namespace-definition: [C++ 7.3: basic.namespace] 26/// named-namespace-definition 27/// unnamed-namespace-definition 28/// 29/// unnamed-namespace-definition: 30/// 'namespace' attributes[opt] '{' namespace-body '}' 31/// 32/// named-namespace-definition: 33/// original-namespace-definition 34/// extension-namespace-definition 35/// 36/// original-namespace-definition: 37/// 'namespace' identifier attributes[opt] '{' namespace-body '}' 38/// 39/// extension-namespace-definition: 40/// 'namespace' original-namespace-name '{' namespace-body '}' 41/// 42/// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 43/// 'namespace' identifier '=' qualified-namespace-specifier ';' 44/// 45Parser::DeclPtrTy Parser::ParseNamespace(unsigned Context, 46 SourceLocation &DeclEnd) { 47 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 48 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 49 50 SourceLocation IdentLoc; 51 IdentifierInfo *Ident = 0; 52 53 Token attrTok; 54 55 if (Tok.is(tok::identifier)) { 56 Ident = Tok.getIdentifierInfo(); 57 IdentLoc = ConsumeToken(); // eat the identifier. 58 } 59 60 // Read label attributes, if present. 61 Action::AttrTy *AttrList = 0; 62 if (Tok.is(tok::kw___attribute)) { 63 attrTok = Tok; 64 65 // FIXME: save these somewhere. 66 AttrList = ParseAttributes(); 67 } 68 69 if (Tok.is(tok::equal)) { 70 if (AttrList) 71 Diag(attrTok, diag::err_unexpected_namespace_attributes_alias); 72 73 return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); 74 } 75 76 if (Tok.isNot(tok::l_brace)) { 77 Diag(Tok, Ident ? diag::err_expected_lbrace : 78 diag::err_expected_ident_lbrace); 79 return DeclPtrTy(); 80 } 81 82 SourceLocation LBrace = ConsumeBrace(); 83 84 // Enter a scope for the namespace. 85 ParseScope NamespaceScope(this, Scope::DeclScope); 86 87 DeclPtrTy NamespcDecl = 88 Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace); 89 90 PrettyStackTraceActionsDecl CrashInfo(NamespcDecl, NamespaceLoc, Actions, 91 PP.getSourceManager(), 92 "parsing namespace"); 93 94 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) 95 ParseExternalDeclaration(); 96 97 // Leave the namespace scope. 98 NamespaceScope.Exit(); 99 100 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBrace); 101 Actions.ActOnFinishNamespaceDef(NamespcDecl, RBraceLoc); 102 103 DeclEnd = RBraceLoc; 104 return NamespcDecl; 105} 106 107/// ParseNamespaceAlias - Parse the part after the '=' in a namespace 108/// alias definition. 109/// 110Parser::DeclPtrTy Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, 111 SourceLocation AliasLoc, 112 IdentifierInfo *Alias, 113 SourceLocation &DeclEnd) { 114 assert(Tok.is(tok::equal) && "Not equal token"); 115 116 ConsumeToken(); // eat the '='. 117 118 CXXScopeSpec SS; 119 // Parse (optional) nested-name-specifier. 120 ParseOptionalCXXScopeSpecifier(SS); 121 122 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 123 Diag(Tok, diag::err_expected_namespace_name); 124 // Skip to end of the definition and eat the ';'. 125 SkipUntil(tok::semi); 126 return DeclPtrTy(); 127 } 128 129 // Parse identifier. 130 IdentifierInfo *Ident = Tok.getIdentifierInfo(); 131 SourceLocation IdentLoc = ConsumeToken(); 132 133 // Eat the ';'. 134 DeclEnd = Tok.getLocation(); 135 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name, 136 "", tok::semi); 137 138 return Actions.ActOnNamespaceAliasDef(CurScope, NamespaceLoc, AliasLoc, Alias, 139 SS, IdentLoc, Ident); 140} 141 142/// ParseLinkage - We know that the current token is a string_literal 143/// and just before that, that extern was seen. 144/// 145/// linkage-specification: [C++ 7.5p2: dcl.link] 146/// 'extern' string-literal '{' declaration-seq[opt] '}' 147/// 'extern' string-literal declaration 148/// 149Parser::DeclPtrTy Parser::ParseLinkage(unsigned Context) { 150 assert(Tok.is(tok::string_literal) && "Not a string literal!"); 151 llvm::SmallVector<char, 8> LangBuffer; 152 // LangBuffer is guaranteed to be big enough. 153 LangBuffer.resize(Tok.getLength()); 154 const char *LangBufPtr = &LangBuffer[0]; 155 unsigned StrSize = PP.getSpelling(Tok, LangBufPtr); 156 157 SourceLocation Loc = ConsumeStringToken(); 158 159 ParseScope LinkageScope(this, Scope::DeclScope); 160 DeclPtrTy LinkageSpec 161 = Actions.ActOnStartLinkageSpecification(CurScope, 162 /*FIXME: */SourceLocation(), 163 Loc, LangBufPtr, StrSize, 164 Tok.is(tok::l_brace)? Tok.getLocation() 165 : SourceLocation()); 166 167 if (Tok.isNot(tok::l_brace)) { 168 ParseDeclarationOrFunctionDefinition(); 169 return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, 170 SourceLocation()); 171 } 172 173 SourceLocation LBrace = ConsumeBrace(); 174 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 175 ParseExternalDeclaration(); 176 } 177 178 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace); 179 return Actions.ActOnFinishLinkageSpecification(CurScope, LinkageSpec, RBrace); 180} 181 182/// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or 183/// using-directive. Assumes that current token is 'using'. 184Parser::DeclPtrTy Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, 185 SourceLocation &DeclEnd) { 186 assert(Tok.is(tok::kw_using) && "Not using token"); 187 188 // Eat 'using'. 189 SourceLocation UsingLoc = ConsumeToken(); 190 191 if (Tok.is(tok::kw_namespace)) 192 // Next token after 'using' is 'namespace' so it must be using-directive 193 return ParseUsingDirective(Context, UsingLoc, DeclEnd); 194 195 // Otherwise, it must be using-declaration. 196 return ParseUsingDeclaration(Context, UsingLoc, DeclEnd); 197} 198 199/// ParseUsingDirective - Parse C++ using-directive, assumes 200/// that current token is 'namespace' and 'using' was already parsed. 201/// 202/// using-directive: [C++ 7.3.p4: namespace.udir] 203/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 204/// namespace-name ; 205/// [GNU] using-directive: 206/// 'using' 'namespace' ::[opt] nested-name-specifier[opt] 207/// namespace-name attributes[opt] ; 208/// 209Parser::DeclPtrTy Parser::ParseUsingDirective(unsigned Context, 210 SourceLocation UsingLoc, 211 SourceLocation &DeclEnd) { 212 assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); 213 214 // Eat 'namespace'. 215 SourceLocation NamespcLoc = ConsumeToken(); 216 217 CXXScopeSpec SS; 218 // Parse (optional) nested-name-specifier. 219 ParseOptionalCXXScopeSpecifier(SS); 220 221 AttributeList *AttrList = 0; 222 IdentifierInfo *NamespcName = 0; 223 SourceLocation IdentLoc = SourceLocation(); 224 225 // Parse namespace-name. 226 if (SS.isInvalid() || Tok.isNot(tok::identifier)) { 227 Diag(Tok, diag::err_expected_namespace_name); 228 // If there was invalid namespace name, skip to end of decl, and eat ';'. 229 SkipUntil(tok::semi); 230 // FIXME: Are there cases, when we would like to call ActOnUsingDirective? 231 return DeclPtrTy(); 232 } 233 234 // Parse identifier. 235 NamespcName = Tok.getIdentifierInfo(); 236 IdentLoc = ConsumeToken(); 237 238 // Parse (optional) attributes (most likely GNU strong-using extension). 239 if (Tok.is(tok::kw___attribute)) 240 AttrList = ParseAttributes(); 241 242 // Eat ';'. 243 DeclEnd = Tok.getLocation(); 244 ExpectAndConsume(tok::semi, 245 AttrList ? diag::err_expected_semi_after_attribute_list : 246 diag::err_expected_semi_after_namespace_name, "", tok::semi); 247 248 return Actions.ActOnUsingDirective(CurScope, UsingLoc, NamespcLoc, SS, 249 IdentLoc, NamespcName, AttrList); 250} 251 252/// ParseUsingDeclaration - Parse C++ using-declaration. Assumes that 253/// 'using' was already seen. 254/// 255/// using-declaration: [C++ 7.3.p3: namespace.udecl] 256/// 'using' 'typename'[opt] ::[opt] nested-name-specifier 257/// unqualified-id 258/// 'using' :: unqualified-id 259/// 260Parser::DeclPtrTy Parser::ParseUsingDeclaration(unsigned Context, 261 SourceLocation UsingLoc, 262 SourceLocation &DeclEnd) { 263 CXXScopeSpec SS; 264 bool IsTypeName; 265 266 // Ignore optional 'typename'. 267 if (Tok.is(tok::kw_typename)) { 268 ConsumeToken(); 269 IsTypeName = true; 270 } 271 else 272 IsTypeName = false; 273 274 // Parse nested-name-specifier. 275 ParseOptionalCXXScopeSpecifier(SS); 276 277 AttributeList *AttrList = 0; 278 279 // Check nested-name specifier. 280 if (SS.isInvalid()) { 281 SkipUntil(tok::semi); 282 return DeclPtrTy(); 283 } 284 if (Tok.is(tok::annot_template_id)) { 285 Diag(Tok, diag::err_unexpected_template_spec_in_using); 286 SkipUntil(tok::semi); 287 return DeclPtrTy(); 288 } 289 290 IdentifierInfo *TargetName = 0; 291 OverloadedOperatorKind Op = OO_None; 292 SourceLocation IdentLoc; 293 294 if (Tok.is(tok::kw_operator)) { 295 IdentLoc = Tok.getLocation(); 296 297 Op = TryParseOperatorFunctionId(); 298 if (!Op) { 299 // If there was an invalid operator, skip to end of decl, and eat ';'. 300 SkipUntil(tok::semi); 301 return DeclPtrTy(); 302 } 303 } else if (Tok.is(tok::identifier)) { 304 // Parse identifier. 305 TargetName = Tok.getIdentifierInfo(); 306 IdentLoc = ConsumeToken(); 307 } else { 308 // FIXME: Use a better diagnostic here. 309 Diag(Tok, diag::err_expected_ident_in_using); 310 311 // If there was invalid identifier, skip to end of decl, and eat ';'. 312 SkipUntil(tok::semi); 313 return DeclPtrTy(); 314 } 315 316 // Parse (optional) attributes (most likely GNU strong-using extension). 317 if (Tok.is(tok::kw___attribute)) 318 AttrList = ParseAttributes(); 319 320 // Eat ';'. 321 DeclEnd = Tok.getLocation(); 322 ExpectAndConsume(tok::semi, diag::err_expected_semi_after, 323 AttrList ? "attributes list" : "namespace name", tok::semi); 324 325 return Actions.ActOnUsingDeclaration(CurScope, UsingLoc, SS, 326 IdentLoc, TargetName, Op, 327 AttrList, IsTypeName); 328} 329 330/// ParseStaticAssertDeclaration - Parse C++0x static_assert-declaratoion. 331/// 332/// static_assert-declaration: 333/// static_assert ( constant-expression , string-literal ) ; 334/// 335Parser::DeclPtrTy Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ 336 assert(Tok.is(tok::kw_static_assert) && "Not a static_assert declaration"); 337 SourceLocation StaticAssertLoc = ConsumeToken(); 338 339 if (Tok.isNot(tok::l_paren)) { 340 Diag(Tok, diag::err_expected_lparen); 341 return DeclPtrTy(); 342 } 343 344 SourceLocation LParenLoc = ConsumeParen(); 345 346 OwningExprResult AssertExpr(ParseConstantExpression()); 347 if (AssertExpr.isInvalid()) { 348 SkipUntil(tok::semi); 349 return DeclPtrTy(); 350 } 351 352 if (ExpectAndConsume(tok::comma, diag::err_expected_comma, "", tok::semi)) 353 return DeclPtrTy(); 354 355 if (Tok.isNot(tok::string_literal)) { 356 Diag(Tok, diag::err_expected_string_literal); 357 SkipUntil(tok::semi); 358 return DeclPtrTy(); 359 } 360 361 OwningExprResult AssertMessage(ParseStringLiteralExpression()); 362 if (AssertMessage.isInvalid()) 363 return DeclPtrTy(); 364 365 MatchRHSPunctuation(tok::r_paren, LParenLoc); 366 367 DeclEnd = Tok.getLocation(); 368 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_static_assert); 369 370 return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, move(AssertExpr), 371 move(AssertMessage)); 372} 373 374/// ParseDecltypeSpecifier - Parse a C++0x decltype specifier. 375/// 376/// 'decltype' ( expression ) 377/// 378void Parser::ParseDecltypeSpecifier(DeclSpec &DS) { 379 assert(Tok.is(tok::kw_decltype) && "Not a decltype specifier"); 380 381 SourceLocation StartLoc = ConsumeToken(); 382 SourceLocation LParenLoc = Tok.getLocation(); 383 384 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, 385 "decltype")) { 386 SkipUntil(tok::r_paren); 387 return; 388 } 389 390 // Parse the expression 391 392 // C++0x [dcl.type.simple]p4: 393 // The operand of the decltype specifier is an unevaluated operand. 394 EnterExpressionEvaluationContext Unevaluated(Actions, 395 Action::Unevaluated); 396 OwningExprResult Result = ParseExpression(); 397 if (Result.isInvalid()) { 398 SkipUntil(tok::r_paren); 399 return; 400 } 401 402 // Match the ')' 403 SourceLocation RParenLoc; 404 if (Tok.is(tok::r_paren)) 405 RParenLoc = ConsumeParen(); 406 else 407 MatchRHSPunctuation(tok::r_paren, LParenLoc); 408 409 if (RParenLoc.isInvalid()) 410 return; 411 412 const char *PrevSpec = 0; 413 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 414 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 415 Result.release())) 416 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 417} 418 419/// ParseClassName - Parse a C++ class-name, which names a class. Note 420/// that we only check that the result names a type; semantic analysis 421/// will need to verify that the type names a class. The result is 422/// either a type or NULL, depending on whether a type name was 423/// found. 424/// 425/// class-name: [C++ 9.1] 426/// identifier 427/// simple-template-id 428/// 429Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, 430 const CXXScopeSpec *SS) { 431 // Check whether we have a template-id that names a type. 432 if (Tok.is(tok::annot_template_id)) { 433 TemplateIdAnnotation *TemplateId 434 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 435 if (TemplateId->Kind == TNK_Type_template) { 436 AnnotateTemplateIdTokenAsType(SS); 437 438 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 439 TypeTy *Type = Tok.getAnnotationValue(); 440 EndLocation = Tok.getAnnotationEndLoc(); 441 ConsumeToken(); 442 443 if (Type) 444 return Type; 445 return true; 446 } 447 448 // Fall through to produce an error below. 449 } 450 451 if (Tok.isNot(tok::identifier)) { 452 Diag(Tok, diag::err_expected_class_name); 453 return true; 454 } 455 456 // We have an identifier; check whether it is actually a type. 457 TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(), 458 Tok.getLocation(), CurScope, SS); 459 if (!Type) { 460 Diag(Tok, diag::err_expected_class_name); 461 return true; 462 } 463 464 // Consume the identifier. 465 EndLocation = ConsumeToken(); 466 return Type; 467} 468 469/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 470/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 471/// until we reach the start of a definition or see a token that 472/// cannot start a definition. 473/// 474/// class-specifier: [C++ class] 475/// class-head '{' member-specification[opt] '}' 476/// class-head '{' member-specification[opt] '}' attributes[opt] 477/// class-head: 478/// class-key identifier[opt] base-clause[opt] 479/// class-key nested-name-specifier identifier base-clause[opt] 480/// class-key nested-name-specifier[opt] simple-template-id 481/// base-clause[opt] 482/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 483/// [GNU] class-key attributes[opt] nested-name-specifier 484/// identifier base-clause[opt] 485/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 486/// simple-template-id base-clause[opt] 487/// class-key: 488/// 'class' 489/// 'struct' 490/// 'union' 491/// 492/// elaborated-type-specifier: [C++ dcl.type.elab] 493/// class-key ::[opt] nested-name-specifier[opt] identifier 494/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 495/// simple-template-id 496/// 497/// Note that the C++ class-specifier and elaborated-type-specifier, 498/// together, subsume the C99 struct-or-union-specifier: 499/// 500/// struct-or-union-specifier: [C99 6.7.2.1] 501/// struct-or-union identifier[opt] '{' struct-contents '}' 502/// struct-or-union identifier 503/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 504/// '}' attributes[opt] 505/// [GNU] struct-or-union attributes[opt] identifier 506/// struct-or-union: 507/// 'struct' 508/// 'union' 509void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 510 SourceLocation StartLoc, DeclSpec &DS, 511 const ParsedTemplateInfo &TemplateInfo, 512 AccessSpecifier AS) { 513 DeclSpec::TST TagType; 514 if (TagTokKind == tok::kw_struct) 515 TagType = DeclSpec::TST_struct; 516 else if (TagTokKind == tok::kw_class) 517 TagType = DeclSpec::TST_class; 518 else { 519 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 520 TagType = DeclSpec::TST_union; 521 } 522 523 AttributeList *Attr = 0; 524 // If attributes exist after tag, parse them. 525 if (Tok.is(tok::kw___attribute)) 526 Attr = ParseAttributes(); 527 528 // If declspecs exist after tag, parse them. 529 if (Tok.is(tok::kw___declspec)) 530 Attr = ParseMicrosoftDeclSpec(Attr); 531 532 // Parse the (optional) nested-name-specifier. 533 CXXScopeSpec SS; 534 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) 535 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 536 Diag(Tok, diag::err_expected_ident); 537 538 // Parse the (optional) class name or simple-template-id. 539 IdentifierInfo *Name = 0; 540 SourceLocation NameLoc; 541 TemplateIdAnnotation *TemplateId = 0; 542 if (Tok.is(tok::identifier)) { 543 Name = Tok.getIdentifierInfo(); 544 NameLoc = ConsumeToken(); 545 } else if (Tok.is(tok::annot_template_id)) { 546 TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 547 NameLoc = ConsumeToken(); 548 549 if (TemplateId->Kind != TNK_Type_template) { 550 // The template-name in the simple-template-id refers to 551 // something other than a class template. Give an appropriate 552 // error message and skip to the ';'. 553 SourceRange Range(NameLoc); 554 if (SS.isNotEmpty()) 555 Range.setBegin(SS.getBeginLoc()); 556 557 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 558 << Name << static_cast<int>(TemplateId->Kind) << Range; 559 560 DS.SetTypeSpecError(); 561 SkipUntil(tok::semi, false, true); 562 TemplateId->Destroy(); 563 return; 564 } 565 } 566 567 // There are three options here. If we have 'struct foo;', then 568 // this is a forward declaration. If we have 'struct foo {...' or 569 // 'struct foo :...' then this is a definition. Otherwise we have 570 // something like 'struct foo xyz', a reference. 571 Action::TagKind TK; 572 if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))) 573 TK = Action::TK_Definition; 574 else if (Tok.is(tok::semi) && !DS.isFriendSpecified()) 575 TK = Action::TK_Declaration; 576 else 577 TK = Action::TK_Reference; 578 579 if (!Name && !TemplateId && TK != Action::TK_Definition) { 580 // We have a declaration or reference to an anonymous class. 581 Diag(StartLoc, diag::err_anon_type_definition) 582 << DeclSpec::getSpecifierName(TagType); 583 584 // Skip the rest of this declarator, up until the comma or semicolon. 585 SkipUntil(tok::comma, true); 586 587 if (TemplateId) 588 TemplateId->Destroy(); 589 return; 590 } 591 592 // Create the tag portion of the class or class template. 593 Action::DeclResult TagOrTempResult; 594 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 595 596 // FIXME: When TK == TK_Reference and we have a template-id, we need 597 // to turn that template-id into a type. 598 599 bool Owned = false; 600 if (TemplateId && TK != Action::TK_Reference) { 601 // Explicit specialization, class template partial specialization, 602 // or explicit instantiation. 603 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 604 TemplateId->getTemplateArgs(), 605 TemplateId->getTemplateArgIsType(), 606 TemplateId->NumArgs); 607 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 608 TK == Action::TK_Declaration) { 609 // This is an explicit instantiation of a class template. 610 TagOrTempResult 611 = Actions.ActOnExplicitInstantiation(CurScope, 612 TemplateInfo.TemplateLoc, 613 TagType, 614 StartLoc, 615 SS, 616 TemplateTy::make(TemplateId->Template), 617 TemplateId->TemplateNameLoc, 618 TemplateId->LAngleLoc, 619 TemplateArgsPtr, 620 TemplateId->getTemplateArgLocations(), 621 TemplateId->RAngleLoc, 622 Attr); 623 } else { 624 // This is an explicit specialization or a class template 625 // partial specialization. 626 TemplateParameterLists FakedParamLists; 627 628 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 629 // This looks like an explicit instantiation, because we have 630 // something like 631 // 632 // template class Foo<X> 633 // 634 // but it actually has a definition. Most likely, this was 635 // meant to be an explicit specialization, but the user forgot 636 // the '<>' after 'template'. 637 assert(TK == Action::TK_Definition && "Expected a definition here"); 638 639 SourceLocation LAngleLoc 640 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 641 Diag(TemplateId->TemplateNameLoc, 642 diag::err_explicit_instantiation_with_definition) 643 << SourceRange(TemplateInfo.TemplateLoc) 644 << CodeModificationHint::CreateInsertion(LAngleLoc, "<>"); 645 646 // Create a fake template parameter list that contains only 647 // "template<>", so that we treat this construct as a class 648 // template specialization. 649 FakedParamLists.push_back( 650 Actions.ActOnTemplateParameterList(0, SourceLocation(), 651 TemplateInfo.TemplateLoc, 652 LAngleLoc, 653 0, 0, 654 LAngleLoc)); 655 TemplateParams = &FakedParamLists; 656 } 657 658 // Build the class template specialization. 659 TagOrTempResult 660 = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TK, 661 StartLoc, SS, 662 TemplateTy::make(TemplateId->Template), 663 TemplateId->TemplateNameLoc, 664 TemplateId->LAngleLoc, 665 TemplateArgsPtr, 666 TemplateId->getTemplateArgLocations(), 667 TemplateId->RAngleLoc, 668 Attr, 669 Action::MultiTemplateParamsArg(Actions, 670 TemplateParams? &(*TemplateParams)[0] : 0, 671 TemplateParams? TemplateParams->size() : 0)); 672 } 673 TemplateId->Destroy(); 674 } else if (TemplateParams && TK != Action::TK_Reference) { 675 // Class template declaration or definition. 676 TagOrTempResult = Actions.ActOnClassTemplate(CurScope, TagType, TK, 677 StartLoc, SS, Name, NameLoc, 678 Attr, 679 Action::MultiTemplateParamsArg(Actions, 680 &(*TemplateParams)[0], 681 TemplateParams->size()), 682 AS); 683 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 684 TK == Action::TK_Declaration) { 685 // Explicit instantiation of a member of a class template 686 // specialization, e.g., 687 // 688 // template struct Outer<int>::Inner; 689 // 690 TagOrTempResult 691 = Actions.ActOnExplicitInstantiation(CurScope, 692 TemplateInfo.TemplateLoc, 693 TagType, StartLoc, SS, Name, 694 NameLoc, Attr); 695 } else { 696 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 697 TK == Action::TK_Definition) { 698 // FIXME: Diagnose this particular error. 699 } 700 701 // Declaration or definition of a class type 702 TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, SS, 703 Name, NameLoc, Attr, AS, Owned); 704 } 705 706 // Parse the optional base clause (C++ only). 707 if (getLang().CPlusPlus && Tok.is(tok::colon)) 708 ParseBaseClause(TagOrTempResult.get()); 709 710 // If there is a body, parse it and inform the actions module. 711 if (Tok.is(tok::l_brace)) 712 if (getLang().CPlusPlus) 713 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 714 else 715 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 716 else if (TK == Action::TK_Definition) { 717 // FIXME: Complain that we have a base-specifier list but no 718 // definition. 719 Diag(Tok, diag::err_expected_lbrace); 720 } 721 722 const char *PrevSpec = 0; 723 if (TagOrTempResult.isInvalid()) { 724 DS.SetTypeSpecError(); 725 return; 726 } 727 728 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, 729 TagOrTempResult.get().getAs<void>(), Owned)) 730 Diag(StartLoc, diag::err_invalid_decl_spec_combination) << PrevSpec; 731 732 if (DS.isFriendSpecified()) 733 Actions.ActOnFriendDecl(CurScope, DS.getFriendSpecLoc(), 734 TagOrTempResult.get()); 735} 736 737/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 738/// 739/// base-clause : [C++ class.derived] 740/// ':' base-specifier-list 741/// base-specifier-list: 742/// base-specifier '...'[opt] 743/// base-specifier-list ',' base-specifier '...'[opt] 744void Parser::ParseBaseClause(DeclPtrTy ClassDecl) { 745 assert(Tok.is(tok::colon) && "Not a base clause"); 746 ConsumeToken(); 747 748 // Build up an array of parsed base specifiers. 749 llvm::SmallVector<BaseTy *, 8> BaseInfo; 750 751 while (true) { 752 // Parse a base-specifier. 753 BaseResult Result = ParseBaseSpecifier(ClassDecl); 754 if (Result.isInvalid()) { 755 // Skip the rest of this base specifier, up until the comma or 756 // opening brace. 757 SkipUntil(tok::comma, tok::l_brace, true, true); 758 } else { 759 // Add this to our array of base specifiers. 760 BaseInfo.push_back(Result.get()); 761 } 762 763 // If the next token is a comma, consume it and keep reading 764 // base-specifiers. 765 if (Tok.isNot(tok::comma)) break; 766 767 // Consume the comma. 768 ConsumeToken(); 769 } 770 771 // Attach the base specifiers 772 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 773} 774 775/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 776/// one entry in the base class list of a class specifier, for example: 777/// class foo : public bar, virtual private baz { 778/// 'public bar' and 'virtual private baz' are each base-specifiers. 779/// 780/// base-specifier: [C++ class.derived] 781/// ::[opt] nested-name-specifier[opt] class-name 782/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 783/// class-name 784/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 785/// class-name 786Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { 787 bool IsVirtual = false; 788 SourceLocation StartLoc = Tok.getLocation(); 789 790 // Parse the 'virtual' keyword. 791 if (Tok.is(tok::kw_virtual)) { 792 ConsumeToken(); 793 IsVirtual = true; 794 } 795 796 // Parse an (optional) access specifier. 797 AccessSpecifier Access = getAccessSpecifierIfPresent(); 798 if (Access) 799 ConsumeToken(); 800 801 // Parse the 'virtual' keyword (again!), in case it came after the 802 // access specifier. 803 if (Tok.is(tok::kw_virtual)) { 804 SourceLocation VirtualLoc = ConsumeToken(); 805 if (IsVirtual) { 806 // Complain about duplicate 'virtual' 807 Diag(VirtualLoc, diag::err_dup_virtual) 808 << CodeModificationHint::CreateRemoval(SourceRange(VirtualLoc)); 809 } 810 811 IsVirtual = true; 812 } 813 814 // Parse optional '::' and optional nested-name-specifier. 815 CXXScopeSpec SS; 816 ParseOptionalCXXScopeSpecifier(SS); 817 818 // The location of the base class itself. 819 SourceLocation BaseLoc = Tok.getLocation(); 820 821 // Parse the class-name. 822 SourceLocation EndLocation; 823 TypeResult BaseType = ParseClassName(EndLocation, &SS); 824 if (BaseType.isInvalid()) 825 return true; 826 827 // Find the complete source range for the base-specifier. 828 SourceRange Range(StartLoc, EndLocation); 829 830 // Notify semantic analysis that we have parsed a complete 831 // base-specifier. 832 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 833 BaseType.get(), BaseLoc); 834} 835 836/// getAccessSpecifierIfPresent - Determine whether the next token is 837/// a C++ access-specifier. 838/// 839/// access-specifier: [C++ class.derived] 840/// 'private' 841/// 'protected' 842/// 'public' 843AccessSpecifier Parser::getAccessSpecifierIfPresent() const 844{ 845 switch (Tok.getKind()) { 846 default: return AS_none; 847 case tok::kw_private: return AS_private; 848 case tok::kw_protected: return AS_protected; 849 case tok::kw_public: return AS_public; 850 } 851} 852 853/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 854/// 855/// member-declaration: 856/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 857/// function-definition ';'[opt] 858/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 859/// using-declaration [TODO] 860/// [C++0x] static_assert-declaration 861/// template-declaration 862/// [GNU] '__extension__' member-declaration 863/// 864/// member-declarator-list: 865/// member-declarator 866/// member-declarator-list ',' member-declarator 867/// 868/// member-declarator: 869/// declarator pure-specifier[opt] 870/// declarator constant-initializer[opt] 871/// identifier[opt] ':' constant-expression 872/// 873/// pure-specifier: 874/// '= 0' 875/// 876/// constant-initializer: 877/// '=' constant-expression 878/// 879void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) { 880 // static_assert-declaration 881 if (Tok.is(tok::kw_static_assert)) { 882 SourceLocation DeclEnd; 883 ParseStaticAssertDeclaration(DeclEnd); 884 return; 885 } 886 887 if (Tok.is(tok::kw_template)) { 888 SourceLocation DeclEnd; 889 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 890 AS); 891 return; 892 } 893 894 // Handle: member-declaration ::= '__extension__' member-declaration 895 if (Tok.is(tok::kw___extension__)) { 896 // __extension__ silences extension warnings in the subexpression. 897 ExtensionRAIIObject O(Diags); // Use RAII to do this. 898 ConsumeToken(); 899 return ParseCXXClassMemberDeclaration(AS); 900 } 901 902 if (Tok.is(tok::kw_using)) { 903 // Eat 'using'. 904 SourceLocation UsingLoc = ConsumeToken(); 905 906 if (Tok.is(tok::kw_namespace)) { 907 Diag(UsingLoc, diag::err_using_namespace_in_class); 908 SkipUntil(tok::semi, true, true); 909 } 910 else { 911 SourceLocation DeclEnd; 912 // Otherwise, it must be using-declaration. 913 ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd); 914 } 915 return; 916 } 917 918 SourceLocation DSStart = Tok.getLocation(); 919 // decl-specifier-seq: 920 // Parse the common declaration-specifiers piece. 921 DeclSpec DS; 922 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS); 923 924 if (Tok.is(tok::semi)) { 925 ConsumeToken(); 926 // C++ 9.2p7: The member-declarator-list can be omitted only after a 927 // class-specifier or an enum-specifier or in a friend declaration. 928 // FIXME: Friend declarations. 929 switch (DS.getTypeSpecType()) { 930 case DeclSpec::TST_struct: 931 case DeclSpec::TST_union: 932 case DeclSpec::TST_class: 933 case DeclSpec::TST_enum: 934 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 935 return; 936 default: 937 Diag(DSStart, diag::err_no_declarators); 938 return; 939 } 940 } 941 942 Declarator DeclaratorInfo(DS, Declarator::MemberContext); 943 944 if (Tok.isNot(tok::colon)) { 945 // Parse the first declarator. 946 ParseDeclarator(DeclaratorInfo); 947 // Error parsing the declarator? 948 if (!DeclaratorInfo.hasName()) { 949 // If so, skip until the semi-colon or a }. 950 SkipUntil(tok::r_brace, true); 951 if (Tok.is(tok::semi)) 952 ConsumeToken(); 953 return; 954 } 955 956 // function-definition: 957 if (Tok.is(tok::l_brace) 958 || (DeclaratorInfo.isFunctionDeclarator() && 959 (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) { 960 if (!DeclaratorInfo.isFunctionDeclarator()) { 961 Diag(Tok, diag::err_func_def_no_params); 962 ConsumeBrace(); 963 SkipUntil(tok::r_brace, true); 964 return; 965 } 966 967 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 968 Diag(Tok, diag::err_function_declared_typedef); 969 // This recovery skips the entire function body. It would be nice 970 // to simply call ParseCXXInlineMethodDef() below, however Sema 971 // assumes the declarator represents a function, not a typedef. 972 ConsumeBrace(); 973 SkipUntil(tok::r_brace, true); 974 return; 975 } 976 977 ParseCXXInlineMethodDef(AS, DeclaratorInfo); 978 return; 979 } 980 } 981 982 // member-declarator-list: 983 // member-declarator 984 // member-declarator-list ',' member-declarator 985 986 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup; 987 OwningExprResult BitfieldSize(Actions); 988 OwningExprResult Init(Actions); 989 bool Deleted = false; 990 991 while (1) { 992 993 // member-declarator: 994 // declarator pure-specifier[opt] 995 // declarator constant-initializer[opt] 996 // identifier[opt] ':' constant-expression 997 998 if (Tok.is(tok::colon)) { 999 ConsumeToken(); 1000 BitfieldSize = ParseConstantExpression(); 1001 if (BitfieldSize.isInvalid()) 1002 SkipUntil(tok::comma, true, true); 1003 } 1004 1005 // pure-specifier: 1006 // '= 0' 1007 // 1008 // constant-initializer: 1009 // '=' constant-expression 1010 // 1011 // defaulted/deleted function-definition: 1012 // '=' 'default' [TODO] 1013 // '=' 'delete' 1014 1015 if (Tok.is(tok::equal)) { 1016 ConsumeToken(); 1017 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 1018 ConsumeToken(); 1019 Deleted = true; 1020 } else { 1021 Init = ParseInitializer(); 1022 if (Init.isInvalid()) 1023 SkipUntil(tok::comma, true, true); 1024 } 1025 } 1026 1027 // If attributes exist after the declarator, parse them. 1028 if (Tok.is(tok::kw___attribute)) { 1029 SourceLocation Loc; 1030 AttributeList *AttrList = ParseAttributes(&Loc); 1031 DeclaratorInfo.AddAttributes(AttrList, Loc); 1032 } 1033 1034 // NOTE: If Sema is the Action module and declarator is an instance field, 1035 // this call will *not* return the created decl; It will return null. 1036 // See Sema::ActOnCXXMemberDeclarator for details. 1037 DeclPtrTy ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS, 1038 DeclaratorInfo, 1039 BitfieldSize.release(), 1040 Init.release(), 1041 Deleted); 1042 if (ThisDecl) 1043 DeclsInGroup.push_back(ThisDecl); 1044 1045 if (DeclaratorInfo.isFunctionDeclarator() && 1046 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1047 != DeclSpec::SCS_typedef) { 1048 // We just declared a member function. If this member function 1049 // has any default arguments, we'll need to parse them later. 1050 LateParsedMethodDeclaration *LateMethod = 0; 1051 DeclaratorChunk::FunctionTypeInfo &FTI 1052 = DeclaratorInfo.getTypeObject(0).Fun; 1053 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1054 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1055 if (!LateMethod) { 1056 // Push this method onto the stack of late-parsed method 1057 // declarations. 1058 getCurrentClass().MethodDecls.push_back( 1059 LateParsedMethodDeclaration(ThisDecl)); 1060 LateMethod = &getCurrentClass().MethodDecls.back(); 1061 1062 // Add all of the parameters prior to this one (they don't 1063 // have default arguments). 1064 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1065 for (unsigned I = 0; I < ParamIdx; ++I) 1066 LateMethod->DefaultArgs.push_back( 1067 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param)); 1068 } 1069 1070 // Add this parameter to the list of parameters (it or may 1071 // not have a default argument). 1072 LateMethod->DefaultArgs.push_back( 1073 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1074 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1075 } 1076 } 1077 } 1078 1079 // If we don't have a comma, it is either the end of the list (a ';') 1080 // or an error, bail out. 1081 if (Tok.isNot(tok::comma)) 1082 break; 1083 1084 // Consume the comma. 1085 ConsumeToken(); 1086 1087 // Parse the next declarator. 1088 DeclaratorInfo.clear(); 1089 BitfieldSize = 0; 1090 Init = 0; 1091 Deleted = false; 1092 1093 // Attributes are only allowed on the second declarator. 1094 if (Tok.is(tok::kw___attribute)) { 1095 SourceLocation Loc; 1096 AttributeList *AttrList = ParseAttributes(&Loc); 1097 DeclaratorInfo.AddAttributes(AttrList, Loc); 1098 } 1099 1100 if (Tok.isNot(tok::colon)) 1101 ParseDeclarator(DeclaratorInfo); 1102 } 1103 1104 if (Tok.is(tok::semi)) { 1105 ConsumeToken(); 1106 Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(), 1107 DeclsInGroup.size()); 1108 return; 1109 } 1110 1111 Diag(Tok, diag::err_expected_semi_decl_list); 1112 // Skip to end of block or statement 1113 SkipUntil(tok::r_brace, true, true); 1114 if (Tok.is(tok::semi)) 1115 ConsumeToken(); 1116 return; 1117} 1118 1119/// ParseCXXMemberSpecification - Parse the class definition. 1120/// 1121/// member-specification: 1122/// member-declaration member-specification[opt] 1123/// access-specifier ':' member-specification[opt] 1124/// 1125void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1126 unsigned TagType, DeclPtrTy TagDecl) { 1127 assert((TagType == DeclSpec::TST_struct || 1128 TagType == DeclSpec::TST_union || 1129 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1130 1131 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1132 PP.getSourceManager(), 1133 "parsing struct/union/class body"); 1134 1135 SourceLocation LBraceLoc = ConsumeBrace(); 1136 1137 // Determine whether this is a top-level (non-nested) class. 1138 bool TopLevelClass = ClassStack.empty() || 1139 CurScope->isInCXXInlineMethodScope(); 1140 1141 // Enter a scope for the class. 1142 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1143 1144 // Note that we are parsing a new (potentially-nested) class definition. 1145 ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass); 1146 1147 if (TagDecl) 1148 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1149 else { 1150 SkipUntil(tok::r_brace, false, false); 1151 return; 1152 } 1153 1154 // C++ 11p3: Members of a class defined with the keyword class are private 1155 // by default. Members of a class defined with the keywords struct or union 1156 // are public by default. 1157 AccessSpecifier CurAS; 1158 if (TagType == DeclSpec::TST_class) 1159 CurAS = AS_private; 1160 else 1161 CurAS = AS_public; 1162 1163 // While we still have something to read, read the member-declarations. 1164 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1165 // Each iteration of this loop reads one member-declaration. 1166 1167 // Check for extraneous top-level semicolon. 1168 if (Tok.is(tok::semi)) { 1169 Diag(Tok, diag::ext_extra_struct_semi); 1170 ConsumeToken(); 1171 continue; 1172 } 1173 1174 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1175 if (AS != AS_none) { 1176 // Current token is a C++ access specifier. 1177 CurAS = AS; 1178 ConsumeToken(); 1179 ExpectAndConsume(tok::colon, diag::err_expected_colon); 1180 continue; 1181 } 1182 1183 // Parse all the comma separated declarators. 1184 ParseCXXClassMemberDeclaration(CurAS); 1185 } 1186 1187 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1188 1189 AttributeList *AttrList = 0; 1190 // If attributes exist after class contents, parse them. 1191 if (Tok.is(tok::kw___attribute)) 1192 AttrList = ParseAttributes(); // FIXME: where should I put them? 1193 1194 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl, 1195 LBraceLoc, RBraceLoc); 1196 1197 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1198 // complete within function bodies, default arguments, 1199 // exception-specifications, and constructor ctor-initializers (including 1200 // such things in nested classes). 1201 // 1202 // FIXME: Only function bodies and constructor ctor-initializers are 1203 // parsed correctly, fix the rest. 1204 if (TopLevelClass) { 1205 // We are not inside a nested class. This class and its nested classes 1206 // are complete and we can parse the delayed portions of method 1207 // declarations and the lexed inline method definitions. 1208 ParseLexedMethodDeclarations(getCurrentClass()); 1209 ParseLexedMethodDefs(getCurrentClass()); 1210 } 1211 1212 // Leave the class scope. 1213 ParsingDef.Pop(); 1214 ClassScope.Exit(); 1215 1216 Actions.ActOnTagFinishDefinition(CurScope, TagDecl); 1217} 1218 1219/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1220/// which explicitly initializes the members or base classes of a 1221/// class (C++ [class.base.init]). For example, the three initializers 1222/// after the ':' in the Derived constructor below: 1223/// 1224/// @code 1225/// class Base { }; 1226/// class Derived : Base { 1227/// int x; 1228/// float f; 1229/// public: 1230/// Derived(float f) : Base(), x(17), f(f) { } 1231/// }; 1232/// @endcode 1233/// 1234/// [C++] ctor-initializer: 1235/// ':' mem-initializer-list 1236/// 1237/// [C++] mem-initializer-list: 1238/// mem-initializer 1239/// mem-initializer , mem-initializer-list 1240void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { 1241 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1242 1243 SourceLocation ColonLoc = ConsumeToken(); 1244 1245 llvm::SmallVector<MemInitTy*, 4> MemInitializers; 1246 1247 do { 1248 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1249 if (!MemInit.isInvalid()) 1250 MemInitializers.push_back(MemInit.get()); 1251 1252 if (Tok.is(tok::comma)) 1253 ConsumeToken(); 1254 else if (Tok.is(tok::l_brace)) 1255 break; 1256 else { 1257 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1258 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 1259 SkipUntil(tok::l_brace, true, true); 1260 break; 1261 } 1262 } while (true); 1263 1264 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 1265 MemInitializers.data(), MemInitializers.size()); 1266} 1267 1268/// ParseMemInitializer - Parse a C++ member initializer, which is 1269/// part of a constructor initializer that explicitly initializes one 1270/// member or base class (C++ [class.base.init]). See 1271/// ParseConstructorInitializer for an example. 1272/// 1273/// [C++] mem-initializer: 1274/// mem-initializer-id '(' expression-list[opt] ')' 1275/// 1276/// [C++] mem-initializer-id: 1277/// '::'[opt] nested-name-specifier[opt] class-name 1278/// identifier 1279Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) { 1280 // parse '::'[opt] nested-name-specifier[opt] 1281 CXXScopeSpec SS; 1282 ParseOptionalCXXScopeSpecifier(SS); 1283 TypeTy *TemplateTypeTy = 0; 1284 if (Tok.is(tok::annot_template_id)) { 1285 TemplateIdAnnotation *TemplateId 1286 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1287 if (TemplateId->Kind == TNK_Type_template) { 1288 AnnotateTemplateIdTokenAsType(&SS); 1289 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 1290 TemplateTypeTy = Tok.getAnnotationValue(); 1291 } 1292 // FIXME. May need to check for TNK_Dependent_template as well. 1293 } 1294 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 1295 Diag(Tok, diag::err_expected_member_or_base_name); 1296 return true; 1297 } 1298 1299 // Get the identifier. This may be a member name or a class name, 1300 // but we'll let the semantic analysis determine which it is. 1301 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 1302 SourceLocation IdLoc = ConsumeToken(); 1303 1304 // Parse the '('. 1305 if (Tok.isNot(tok::l_paren)) { 1306 Diag(Tok, diag::err_expected_lparen); 1307 return true; 1308 } 1309 SourceLocation LParenLoc = ConsumeParen(); 1310 1311 // Parse the optional expression-list. 1312 ExprVector ArgExprs(Actions); 1313 CommaLocsTy CommaLocs; 1314 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 1315 SkipUntil(tok::r_paren); 1316 return true; 1317 } 1318 1319 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1320 1321 return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II, 1322 TemplateTypeTy, IdLoc, 1323 LParenLoc, ArgExprs.take(), 1324 ArgExprs.size(), CommaLocs.data(), 1325 RParenLoc); 1326} 1327 1328/// ParseExceptionSpecification - Parse a C++ exception-specification 1329/// (C++ [except.spec]). 1330/// 1331/// exception-specification: 1332/// 'throw' '(' type-id-list [opt] ')' 1333/// [MS] 'throw' '(' '...' ')' 1334/// 1335/// type-id-list: 1336/// type-id 1337/// type-id-list ',' type-id 1338/// 1339bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, 1340 llvm::SmallVector<TypeTy*, 2> 1341 &Exceptions, 1342 llvm::SmallVector<SourceRange, 2> 1343 &Ranges, 1344 bool &hasAnyExceptionSpec) { 1345 assert(Tok.is(tok::kw_throw) && "expected throw"); 1346 1347 SourceLocation ThrowLoc = ConsumeToken(); 1348 1349 if (!Tok.is(tok::l_paren)) { 1350 return Diag(Tok, diag::err_expected_lparen_after) << "throw"; 1351 } 1352 SourceLocation LParenLoc = ConsumeParen(); 1353 1354 // Parse throw(...), a Microsoft extension that means "this function 1355 // can throw anything". 1356 if (Tok.is(tok::ellipsis)) { 1357 hasAnyExceptionSpec = true; 1358 SourceLocation EllipsisLoc = ConsumeToken(); 1359 if (!getLang().Microsoft) 1360 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 1361 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1362 return false; 1363 } 1364 1365 // Parse the sequence of type-ids. 1366 SourceRange Range; 1367 while (Tok.isNot(tok::r_paren)) { 1368 TypeResult Res(ParseTypeName(&Range)); 1369 if (!Res.isInvalid()) { 1370 Exceptions.push_back(Res.get()); 1371 Ranges.push_back(Range); 1372 } 1373 if (Tok.is(tok::comma)) 1374 ConsumeToken(); 1375 else 1376 break; 1377 } 1378 1379 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1380 return false; 1381} 1382 1383/// \brief We have just started parsing the definition of a new class, 1384/// so push that class onto our stack of classes that is currently 1385/// being parsed. 1386void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) { 1387 assert((TopLevelClass || !ClassStack.empty()) && 1388 "Nested class without outer class"); 1389 ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass)); 1390} 1391 1392/// \brief Deallocate the given parsed class and all of its nested 1393/// classes. 1394void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 1395 for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I) 1396 DeallocateParsedClasses(Class->NestedClasses[I]); 1397 delete Class; 1398} 1399 1400/// \brief Pop the top class of the stack of classes that are 1401/// currently being parsed. 1402/// 1403/// This routine should be called when we have finished parsing the 1404/// definition of a class, but have not yet popped the Scope 1405/// associated with the class's definition. 1406/// 1407/// \returns true if the class we've popped is a top-level class, 1408/// false otherwise. 1409void Parser::PopParsingClass() { 1410 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 1411 1412 ParsingClass *Victim = ClassStack.top(); 1413 ClassStack.pop(); 1414 if (Victim->TopLevelClass) { 1415 // Deallocate all of the nested classes of this class, 1416 // recursively: we don't need to keep any of this information. 1417 DeallocateParsedClasses(Victim); 1418 return; 1419 } 1420 assert(!ClassStack.empty() && "Missing top-level class?"); 1421 1422 if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && 1423 Victim->NestedClasses.empty()) { 1424 // The victim is a nested class, but we will not need to perform 1425 // any processing after the definition of this class since it has 1426 // no members whose handling was delayed. Therefore, we can just 1427 // remove this nested class. 1428 delete Victim; 1429 return; 1430 } 1431 1432 // This nested class has some members that will need to be processed 1433 // after the top-level class is completely defined. Therefore, add 1434 // it to the list of nested classes within its parent. 1435 assert(CurScope->isClassScope() && "Nested class outside of class scope?"); 1436 ClassStack.top()->NestedClasses.push_back(Victim); 1437 Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope(); 1438} 1439