ParseDeclCXX.cpp revision fec54013fcd0eb72642741584ca04c1bc292bef8
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 unsigned DiagID; 414 // Check for duplicate type specifiers (e.g. "int decltype(a)"). 415 if (DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, 416 DiagID, Result.release())) 417 Diag(StartLoc, DiagID) << PrevSpec; 418} 419 420/// ParseClassName - Parse a C++ class-name, which names a class. Note 421/// that we only check that the result names a type; semantic analysis 422/// will need to verify that the type names a class. The result is 423/// either a type or NULL, depending on whether a type name was 424/// found. 425/// 426/// class-name: [C++ 9.1] 427/// identifier 428/// simple-template-id 429/// 430Parser::TypeResult Parser::ParseClassName(SourceLocation &EndLocation, 431 const CXXScopeSpec *SS, 432 bool DestrExpected) { 433 // Check whether we have a template-id that names a type. 434 if (Tok.is(tok::annot_template_id)) { 435 TemplateIdAnnotation *TemplateId 436 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 437 if (TemplateId->Kind == TNK_Type_template) { 438 AnnotateTemplateIdTokenAsType(SS); 439 440 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 441 TypeTy *Type = Tok.getAnnotationValue(); 442 EndLocation = Tok.getAnnotationEndLoc(); 443 ConsumeToken(); 444 445 if (Type) 446 return Type; 447 return true; 448 } 449 450 // Fall through to produce an error below. 451 } 452 453 if (Tok.isNot(tok::identifier)) { 454 Diag(Tok, diag::err_expected_class_name); 455 return true; 456 } 457 458 // We have an identifier; check whether it is actually a type. 459 TypeTy *Type = Actions.getTypeName(*Tok.getIdentifierInfo(), 460 Tok.getLocation(), CurScope, SS); 461 if (!Type) { 462 Diag(Tok, DestrExpected ? diag::err_destructor_class_name 463 : diag::err_expected_class_name); 464 return true; 465 } 466 467 // Consume the identifier. 468 EndLocation = ConsumeToken(); 469 return Type; 470} 471 472/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 473/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 474/// until we reach the start of a definition or see a token that 475/// cannot start a definition. 476/// 477/// class-specifier: [C++ class] 478/// class-head '{' member-specification[opt] '}' 479/// class-head '{' member-specification[opt] '}' attributes[opt] 480/// class-head: 481/// class-key identifier[opt] base-clause[opt] 482/// class-key nested-name-specifier identifier base-clause[opt] 483/// class-key nested-name-specifier[opt] simple-template-id 484/// base-clause[opt] 485/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 486/// [GNU] class-key attributes[opt] nested-name-specifier 487/// identifier base-clause[opt] 488/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 489/// simple-template-id base-clause[opt] 490/// class-key: 491/// 'class' 492/// 'struct' 493/// 'union' 494/// 495/// elaborated-type-specifier: [C++ dcl.type.elab] 496/// class-key ::[opt] nested-name-specifier[opt] identifier 497/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 498/// simple-template-id 499/// 500/// Note that the C++ class-specifier and elaborated-type-specifier, 501/// together, subsume the C99 struct-or-union-specifier: 502/// 503/// struct-or-union-specifier: [C99 6.7.2.1] 504/// struct-or-union identifier[opt] '{' struct-contents '}' 505/// struct-or-union identifier 506/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 507/// '}' attributes[opt] 508/// [GNU] struct-or-union attributes[opt] identifier 509/// struct-or-union: 510/// 'struct' 511/// 'union' 512void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, 513 SourceLocation StartLoc, DeclSpec &DS, 514 const ParsedTemplateInfo &TemplateInfo, 515 AccessSpecifier AS) { 516 DeclSpec::TST TagType; 517 if (TagTokKind == tok::kw_struct) 518 TagType = DeclSpec::TST_struct; 519 else if (TagTokKind == tok::kw_class) 520 TagType = DeclSpec::TST_class; 521 else { 522 assert(TagTokKind == tok::kw_union && "Not a class specifier"); 523 TagType = DeclSpec::TST_union; 524 } 525 526 AttributeList *Attr = 0; 527 // If attributes exist after tag, parse them. 528 if (Tok.is(tok::kw___attribute)) 529 Attr = ParseAttributes(); 530 531 // If declspecs exist after tag, parse them. 532 if (Tok.is(tok::kw___declspec)) 533 Attr = ParseMicrosoftDeclSpec(Attr); 534 535 // Parse the (optional) nested-name-specifier. 536 CXXScopeSpec SS; 537 if (getLang().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS)) 538 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 539 Diag(Tok, diag::err_expected_ident); 540 541 // Parse the (optional) class name or simple-template-id. 542 IdentifierInfo *Name = 0; 543 SourceLocation NameLoc; 544 TemplateIdAnnotation *TemplateId = 0; 545 if (Tok.is(tok::identifier)) { 546 Name = Tok.getIdentifierInfo(); 547 NameLoc = ConsumeToken(); 548 } else if (Tok.is(tok::annot_template_id)) { 549 TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 550 NameLoc = ConsumeToken(); 551 552 if (TemplateId->Kind != TNK_Type_template) { 553 // The template-name in the simple-template-id refers to 554 // something other than a class template. Give an appropriate 555 // error message and skip to the ';'. 556 SourceRange Range(NameLoc); 557 if (SS.isNotEmpty()) 558 Range.setBegin(SS.getBeginLoc()); 559 560 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 561 << Name << static_cast<int>(TemplateId->Kind) << Range; 562 563 DS.SetTypeSpecError(); 564 SkipUntil(tok::semi, false, true); 565 TemplateId->Destroy(); 566 return; 567 } 568 } 569 570 // There are three options here. If we have 'struct foo;', then 571 // this is a forward declaration. If we have 'struct foo {...' or 572 // 'struct foo :...' then this is a definition. Otherwise we have 573 // something like 'struct foo xyz', a reference. 574 Action::TagUseKind TUK; 575 if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))) 576 TUK = Action::TUK_Definition; 577 else if (Tok.is(tok::semi) && !DS.isFriendSpecified()) 578 TUK = Action::TUK_Declaration; 579 else 580 TUK = Action::TUK_Reference; 581 582 if (!Name && !TemplateId && TUK != Action::TUK_Definition) { 583 // We have a declaration or reference to an anonymous class. 584 Diag(StartLoc, diag::err_anon_type_definition) 585 << DeclSpec::getSpecifierName(TagType); 586 587 // Skip the rest of this declarator, up until the comma or semicolon. 588 SkipUntil(tok::comma, true); 589 590 if (TemplateId) 591 TemplateId->Destroy(); 592 return; 593 } 594 595 // Create the tag portion of the class or class template. 596 Action::DeclResult TagOrTempResult; 597 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 598 599 // FIXME: When TUK == TUK_Reference and we have a template-id, we need 600 // to turn that template-id into a type. 601 602 bool Owned = false; 603 if (TemplateId && TUK != Action::TUK_Reference) { 604 // Explicit specialization, class template partial specialization, 605 // or explicit instantiation. 606 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 607 TemplateId->getTemplateArgs(), 608 TemplateId->getTemplateArgIsType(), 609 TemplateId->NumArgs); 610 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 611 TUK == Action::TUK_Declaration) { 612 // This is an explicit instantiation of a class template. 613 TagOrTempResult 614 = Actions.ActOnExplicitInstantiation(CurScope, 615 TemplateInfo.TemplateLoc, 616 TagType, 617 StartLoc, 618 SS, 619 TemplateTy::make(TemplateId->Template), 620 TemplateId->TemplateNameLoc, 621 TemplateId->LAngleLoc, 622 TemplateArgsPtr, 623 TemplateId->getTemplateArgLocations(), 624 TemplateId->RAngleLoc, 625 Attr); 626 } else { 627 // This is an explicit specialization or a class template 628 // partial specialization. 629 TemplateParameterLists FakedParamLists; 630 631 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 632 // This looks like an explicit instantiation, because we have 633 // something like 634 // 635 // template class Foo<X> 636 // 637 // but it actually has a definition. Most likely, this was 638 // meant to be an explicit specialization, but the user forgot 639 // the '<>' after 'template'. 640 assert(TUK == Action::TUK_Definition && "Expected a definition here"); 641 642 SourceLocation LAngleLoc 643 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 644 Diag(TemplateId->TemplateNameLoc, 645 diag::err_explicit_instantiation_with_definition) 646 << SourceRange(TemplateInfo.TemplateLoc) 647 << CodeModificationHint::CreateInsertion(LAngleLoc, "<>"); 648 649 // Create a fake template parameter list that contains only 650 // "template<>", so that we treat this construct as a class 651 // template specialization. 652 FakedParamLists.push_back( 653 Actions.ActOnTemplateParameterList(0, SourceLocation(), 654 TemplateInfo.TemplateLoc, 655 LAngleLoc, 656 0, 0, 657 LAngleLoc)); 658 TemplateParams = &FakedParamLists; 659 } 660 661 // Build the class template specialization. 662 TagOrTempResult 663 = Actions.ActOnClassTemplateSpecialization(CurScope, TagType, TUK, 664 StartLoc, SS, 665 TemplateTy::make(TemplateId->Template), 666 TemplateId->TemplateNameLoc, 667 TemplateId->LAngleLoc, 668 TemplateArgsPtr, 669 TemplateId->getTemplateArgLocations(), 670 TemplateId->RAngleLoc, 671 Attr, 672 Action::MultiTemplateParamsArg(Actions, 673 TemplateParams? &(*TemplateParams)[0] : 0, 674 TemplateParams? TemplateParams->size() : 0)); 675 } 676 TemplateId->Destroy(); 677 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 678 TUK == Action::TUK_Declaration) { 679 // Explicit instantiation of a member of a class template 680 // specialization, e.g., 681 // 682 // template struct Outer<int>::Inner; 683 // 684 TagOrTempResult 685 = Actions.ActOnExplicitInstantiation(CurScope, 686 TemplateInfo.TemplateLoc, 687 TagType, StartLoc, SS, Name, 688 NameLoc, Attr); 689 } else { 690 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 691 TUK == Action::TUK_Definition) { 692 // FIXME: Diagnose this particular error. 693 } 694 695 // Declaration or definition of a class type 696 TagOrTempResult = Actions.ActOnTag(CurScope, TagType, TUK, StartLoc, SS, 697 Name, NameLoc, Attr, AS, 698 Action::MultiTemplateParamsArg(Actions, 699 TemplateParams? &(*TemplateParams)[0] : 0, 700 TemplateParams? TemplateParams->size() : 0), 701 Owned); 702 } 703 704 // Parse the optional base clause (C++ only). 705 if (getLang().CPlusPlus && Tok.is(tok::colon)) 706 ParseBaseClause(TagOrTempResult.get()); 707 708 // If there is a body, parse it and inform the actions module. 709 if (Tok.is(tok::l_brace)) 710 if (getLang().CPlusPlus) 711 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 712 else 713 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 714 else if (TUK == Action::TUK_Definition) { 715 // FIXME: Complain that we have a base-specifier list but no 716 // definition. 717 Diag(Tok, diag::err_expected_lbrace); 718 } 719 720 if (TagOrTempResult.isInvalid()) { 721 DS.SetTypeSpecError(); 722 return; 723 } 724 725 const char *PrevSpec = 0; 726 unsigned DiagID; 727 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, DiagID, 728 TagOrTempResult.get().getAs<void>(), Owned)) 729 Diag(StartLoc, DiagID) << PrevSpec; 730 731 if (DS.isFriendSpecified()) 732 Actions.ActOnFriendDecl(CurScope, DS.getFriendSpecLoc(), 733 TagOrTempResult.get()); 734} 735 736/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 737/// 738/// base-clause : [C++ class.derived] 739/// ':' base-specifier-list 740/// base-specifier-list: 741/// base-specifier '...'[opt] 742/// base-specifier-list ',' base-specifier '...'[opt] 743void Parser::ParseBaseClause(DeclPtrTy ClassDecl) { 744 assert(Tok.is(tok::colon) && "Not a base clause"); 745 ConsumeToken(); 746 747 // Build up an array of parsed base specifiers. 748 llvm::SmallVector<BaseTy *, 8> BaseInfo; 749 750 while (true) { 751 // Parse a base-specifier. 752 BaseResult Result = ParseBaseSpecifier(ClassDecl); 753 if (Result.isInvalid()) { 754 // Skip the rest of this base specifier, up until the comma or 755 // opening brace. 756 SkipUntil(tok::comma, tok::l_brace, true, true); 757 } else { 758 // Add this to our array of base specifiers. 759 BaseInfo.push_back(Result.get()); 760 } 761 762 // If the next token is a comma, consume it and keep reading 763 // base-specifiers. 764 if (Tok.isNot(tok::comma)) break; 765 766 // Consume the comma. 767 ConsumeToken(); 768 } 769 770 // Attach the base specifiers 771 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 772} 773 774/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 775/// one entry in the base class list of a class specifier, for example: 776/// class foo : public bar, virtual private baz { 777/// 'public bar' and 'virtual private baz' are each base-specifiers. 778/// 779/// base-specifier: [C++ class.derived] 780/// ::[opt] nested-name-specifier[opt] class-name 781/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 782/// class-name 783/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 784/// class-name 785Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { 786 bool IsVirtual = false; 787 SourceLocation StartLoc = Tok.getLocation(); 788 789 // Parse the 'virtual' keyword. 790 if (Tok.is(tok::kw_virtual)) { 791 ConsumeToken(); 792 IsVirtual = true; 793 } 794 795 // Parse an (optional) access specifier. 796 AccessSpecifier Access = getAccessSpecifierIfPresent(); 797 if (Access) 798 ConsumeToken(); 799 800 // Parse the 'virtual' keyword (again!), in case it came after the 801 // access specifier. 802 if (Tok.is(tok::kw_virtual)) { 803 SourceLocation VirtualLoc = ConsumeToken(); 804 if (IsVirtual) { 805 // Complain about duplicate 'virtual' 806 Diag(VirtualLoc, diag::err_dup_virtual) 807 << CodeModificationHint::CreateRemoval(SourceRange(VirtualLoc)); 808 } 809 810 IsVirtual = true; 811 } 812 813 // Parse optional '::' and optional nested-name-specifier. 814 CXXScopeSpec SS; 815 ParseOptionalCXXScopeSpecifier(SS); 816 817 // The location of the base class itself. 818 SourceLocation BaseLoc = Tok.getLocation(); 819 820 // Parse the class-name. 821 SourceLocation EndLocation; 822 TypeResult BaseType = ParseClassName(EndLocation, &SS); 823 if (BaseType.isInvalid()) 824 return true; 825 826 // Find the complete source range for the base-specifier. 827 SourceRange Range(StartLoc, EndLocation); 828 829 // Notify semantic analysis that we have parsed a complete 830 // base-specifier. 831 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 832 BaseType.get(), BaseLoc); 833} 834 835/// getAccessSpecifierIfPresent - Determine whether the next token is 836/// a C++ access-specifier. 837/// 838/// access-specifier: [C++ class.derived] 839/// 'private' 840/// 'protected' 841/// 'public' 842AccessSpecifier Parser::getAccessSpecifierIfPresent() const 843{ 844 switch (Tok.getKind()) { 845 default: return AS_none; 846 case tok::kw_private: return AS_private; 847 case tok::kw_protected: return AS_protected; 848 case tok::kw_public: return AS_public; 849 } 850} 851 852void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, 853 DeclPtrTy ThisDecl) { 854 // We just declared a member function. If this member function 855 // has any default arguments, we'll need to parse them later. 856 LateParsedMethodDeclaration *LateMethod = 0; 857 DeclaratorChunk::FunctionTypeInfo &FTI 858 = DeclaratorInfo.getTypeObject(0).Fun; 859 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 860 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 861 if (!LateMethod) { 862 // Push this method onto the stack of late-parsed method 863 // declarations. 864 getCurrentClass().MethodDecls.push_back( 865 LateParsedMethodDeclaration(ThisDecl)); 866 LateMethod = &getCurrentClass().MethodDecls.back(); 867 868 // Add all of the parameters prior to this one (they don't 869 // have default arguments). 870 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 871 for (unsigned I = 0; I < ParamIdx; ++I) 872 LateMethod->DefaultArgs.push_back( 873 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param)); 874 } 875 876 // Add this parameter to the list of parameters (it or may 877 // not have a default argument). 878 LateMethod->DefaultArgs.push_back( 879 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 880 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 881 } 882 } 883} 884 885/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 886/// 887/// member-declaration: 888/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 889/// function-definition ';'[opt] 890/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 891/// using-declaration [TODO] 892/// [C++0x] static_assert-declaration 893/// template-declaration 894/// [GNU] '__extension__' member-declaration 895/// 896/// member-declarator-list: 897/// member-declarator 898/// member-declarator-list ',' member-declarator 899/// 900/// member-declarator: 901/// declarator pure-specifier[opt] 902/// declarator constant-initializer[opt] 903/// identifier[opt] ':' constant-expression 904/// 905/// pure-specifier: 906/// '= 0' 907/// 908/// constant-initializer: 909/// '=' constant-expression 910/// 911void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) { 912 // static_assert-declaration 913 if (Tok.is(tok::kw_static_assert)) { 914 SourceLocation DeclEnd; 915 ParseStaticAssertDeclaration(DeclEnd); 916 return; 917 } 918 919 if (Tok.is(tok::kw_template)) { 920 SourceLocation DeclEnd; 921 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 922 AS); 923 return; 924 } 925 926 // Handle: member-declaration ::= '__extension__' member-declaration 927 if (Tok.is(tok::kw___extension__)) { 928 // __extension__ silences extension warnings in the subexpression. 929 ExtensionRAIIObject O(Diags); // Use RAII to do this. 930 ConsumeToken(); 931 return ParseCXXClassMemberDeclaration(AS); 932 } 933 934 if (Tok.is(tok::kw_using)) { 935 // Eat 'using'. 936 SourceLocation UsingLoc = ConsumeToken(); 937 938 if (Tok.is(tok::kw_namespace)) { 939 Diag(UsingLoc, diag::err_using_namespace_in_class); 940 SkipUntil(tok::semi, true, true); 941 } 942 else { 943 SourceLocation DeclEnd; 944 // Otherwise, it must be using-declaration. 945 ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd); 946 } 947 return; 948 } 949 950 SourceLocation DSStart = Tok.getLocation(); 951 // decl-specifier-seq: 952 // Parse the common declaration-specifiers piece. 953 DeclSpec DS; 954 ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS); 955 956 if (Tok.is(tok::semi)) { 957 ConsumeToken(); 958 // C++ 9.2p7: The member-declarator-list can be omitted only after a 959 // class-specifier or an enum-specifier or in a friend declaration. 960 // FIXME: Friend declarations. 961 switch (DS.getTypeSpecType()) { 962 case DeclSpec::TST_struct: 963 case DeclSpec::TST_union: 964 case DeclSpec::TST_class: 965 case DeclSpec::TST_enum: 966 Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 967 return; 968 default: 969 Diag(DSStart, diag::err_no_declarators); 970 return; 971 } 972 } 973 974 Declarator DeclaratorInfo(DS, Declarator::MemberContext); 975 976 if (Tok.isNot(tok::colon)) { 977 // Parse the first declarator. 978 ParseDeclarator(DeclaratorInfo); 979 // Error parsing the declarator? 980 if (!DeclaratorInfo.hasName()) { 981 // If so, skip until the semi-colon or a }. 982 SkipUntil(tok::r_brace, true); 983 if (Tok.is(tok::semi)) 984 ConsumeToken(); 985 return; 986 } 987 988 // function-definition: 989 if (Tok.is(tok::l_brace) 990 || (DeclaratorInfo.isFunctionDeclarator() && 991 (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) { 992 if (!DeclaratorInfo.isFunctionDeclarator()) { 993 Diag(Tok, diag::err_func_def_no_params); 994 ConsumeBrace(); 995 SkipUntil(tok::r_brace, true); 996 return; 997 } 998 999 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1000 Diag(Tok, diag::err_function_declared_typedef); 1001 // This recovery skips the entire function body. It would be nice 1002 // to simply call ParseCXXInlineMethodDef() below, however Sema 1003 // assumes the declarator represents a function, not a typedef. 1004 ConsumeBrace(); 1005 SkipUntil(tok::r_brace, true); 1006 return; 1007 } 1008 1009 ParseCXXInlineMethodDef(AS, DeclaratorInfo); 1010 return; 1011 } 1012 } 1013 1014 // member-declarator-list: 1015 // member-declarator 1016 // member-declarator-list ',' member-declarator 1017 1018 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup; 1019 OwningExprResult BitfieldSize(Actions); 1020 OwningExprResult Init(Actions); 1021 bool Deleted = false; 1022 1023 while (1) { 1024 1025 // member-declarator: 1026 // declarator pure-specifier[opt] 1027 // declarator constant-initializer[opt] 1028 // identifier[opt] ':' constant-expression 1029 1030 if (Tok.is(tok::colon)) { 1031 ConsumeToken(); 1032 BitfieldSize = ParseConstantExpression(); 1033 if (BitfieldSize.isInvalid()) 1034 SkipUntil(tok::comma, true, true); 1035 } 1036 1037 // pure-specifier: 1038 // '= 0' 1039 // 1040 // constant-initializer: 1041 // '=' constant-expression 1042 // 1043 // defaulted/deleted function-definition: 1044 // '=' 'default' [TODO] 1045 // '=' 'delete' 1046 1047 if (Tok.is(tok::equal)) { 1048 ConsumeToken(); 1049 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 1050 ConsumeToken(); 1051 Deleted = true; 1052 } else { 1053 Init = ParseInitializer(); 1054 if (Init.isInvalid()) 1055 SkipUntil(tok::comma, true, true); 1056 } 1057 } 1058 1059 // If attributes exist after the declarator, parse them. 1060 if (Tok.is(tok::kw___attribute)) { 1061 SourceLocation Loc; 1062 AttributeList *AttrList = ParseAttributes(&Loc); 1063 DeclaratorInfo.AddAttributes(AttrList, Loc); 1064 } 1065 1066 // NOTE: If Sema is the Action module and declarator is an instance field, 1067 // this call will *not* return the created decl; It will return null. 1068 // See Sema::ActOnCXXMemberDeclarator for details. 1069 DeclPtrTy ThisDecl = Actions.ActOnCXXMemberDeclarator(CurScope, AS, 1070 DeclaratorInfo, 1071 BitfieldSize.release(), 1072 Init.release(), 1073 Deleted); 1074 if (ThisDecl) 1075 DeclsInGroup.push_back(ThisDecl); 1076 1077 if (DeclaratorInfo.isFunctionDeclarator() && 1078 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1079 != DeclSpec::SCS_typedef) { 1080 HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); 1081 } 1082 1083 // If we don't have a comma, it is either the end of the list (a ';') 1084 // or an error, bail out. 1085 if (Tok.isNot(tok::comma)) 1086 break; 1087 1088 // Consume the comma. 1089 ConsumeToken(); 1090 1091 // Parse the next declarator. 1092 DeclaratorInfo.clear(); 1093 BitfieldSize = 0; 1094 Init = 0; 1095 Deleted = false; 1096 1097 // Attributes are only allowed on the second declarator. 1098 if (Tok.is(tok::kw___attribute)) { 1099 SourceLocation Loc; 1100 AttributeList *AttrList = ParseAttributes(&Loc); 1101 DeclaratorInfo.AddAttributes(AttrList, Loc); 1102 } 1103 1104 if (Tok.isNot(tok::colon)) 1105 ParseDeclarator(DeclaratorInfo); 1106 } 1107 1108 if (Tok.is(tok::semi)) { 1109 ConsumeToken(); 1110 Actions.FinalizeDeclaratorGroup(CurScope, DS, DeclsInGroup.data(), 1111 DeclsInGroup.size()); 1112 return; 1113 } 1114 1115 Diag(Tok, diag::err_expected_semi_decl_list); 1116 // Skip to end of block or statement 1117 SkipUntil(tok::r_brace, true, true); 1118 if (Tok.is(tok::semi)) 1119 ConsumeToken(); 1120 return; 1121} 1122 1123/// ParseCXXMemberSpecification - Parse the class definition. 1124/// 1125/// member-specification: 1126/// member-declaration member-specification[opt] 1127/// access-specifier ':' member-specification[opt] 1128/// 1129void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1130 unsigned TagType, DeclPtrTy TagDecl) { 1131 assert((TagType == DeclSpec::TST_struct || 1132 TagType == DeclSpec::TST_union || 1133 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1134 1135 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1136 PP.getSourceManager(), 1137 "parsing struct/union/class body"); 1138 1139 SourceLocation LBraceLoc = ConsumeBrace(); 1140 1141 // Determine whether this is a top-level (non-nested) class. 1142 bool TopLevelClass = ClassStack.empty() || 1143 CurScope->isInCXXInlineMethodScope(); 1144 1145 // Enter a scope for the class. 1146 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1147 1148 // Note that we are parsing a new (potentially-nested) class definition. 1149 ParsingClassDefinition ParsingDef(*this, TagDecl, TopLevelClass); 1150 1151 if (TagDecl) 1152 Actions.ActOnTagStartDefinition(CurScope, TagDecl); 1153 else { 1154 SkipUntil(tok::r_brace, false, false); 1155 return; 1156 } 1157 1158 // C++ 11p3: Members of a class defined with the keyword class are private 1159 // by default. Members of a class defined with the keywords struct or union 1160 // are public by default. 1161 AccessSpecifier CurAS; 1162 if (TagType == DeclSpec::TST_class) 1163 CurAS = AS_private; 1164 else 1165 CurAS = AS_public; 1166 1167 // While we still have something to read, read the member-declarations. 1168 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1169 // Each iteration of this loop reads one member-declaration. 1170 1171 // Check for extraneous top-level semicolon. 1172 if (Tok.is(tok::semi)) { 1173 Diag(Tok, diag::ext_extra_struct_semi); 1174 ConsumeToken(); 1175 continue; 1176 } 1177 1178 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1179 if (AS != AS_none) { 1180 // Current token is a C++ access specifier. 1181 CurAS = AS; 1182 ConsumeToken(); 1183 ExpectAndConsume(tok::colon, diag::err_expected_colon); 1184 continue; 1185 } 1186 1187 // Parse all the comma separated declarators. 1188 ParseCXXClassMemberDeclaration(CurAS); 1189 } 1190 1191 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1192 1193 AttributeList *AttrList = 0; 1194 // If attributes exist after class contents, parse them. 1195 if (Tok.is(tok::kw___attribute)) 1196 AttrList = ParseAttributes(); // FIXME: where should I put them? 1197 1198 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl, 1199 LBraceLoc, RBraceLoc); 1200 1201 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1202 // complete within function bodies, default arguments, 1203 // exception-specifications, and constructor ctor-initializers (including 1204 // such things in nested classes). 1205 // 1206 // FIXME: Only function bodies and constructor ctor-initializers are 1207 // parsed correctly, fix the rest. 1208 if (TopLevelClass) { 1209 // We are not inside a nested class. This class and its nested classes 1210 // are complete and we can parse the delayed portions of method 1211 // declarations and the lexed inline method definitions. 1212 ParseLexedMethodDeclarations(getCurrentClass()); 1213 ParseLexedMethodDefs(getCurrentClass()); 1214 } 1215 1216 // Leave the class scope. 1217 ParsingDef.Pop(); 1218 ClassScope.Exit(); 1219 1220 Actions.ActOnTagFinishDefinition(CurScope, TagDecl, RBraceLoc); 1221} 1222 1223/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1224/// which explicitly initializes the members or base classes of a 1225/// class (C++ [class.base.init]). For example, the three initializers 1226/// after the ':' in the Derived constructor below: 1227/// 1228/// @code 1229/// class Base { }; 1230/// class Derived : Base { 1231/// int x; 1232/// float f; 1233/// public: 1234/// Derived(float f) : Base(), x(17), f(f) { } 1235/// }; 1236/// @endcode 1237/// 1238/// [C++] ctor-initializer: 1239/// ':' mem-initializer-list 1240/// 1241/// [C++] mem-initializer-list: 1242/// mem-initializer 1243/// mem-initializer , mem-initializer-list 1244void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { 1245 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1246 1247 SourceLocation ColonLoc = ConsumeToken(); 1248 1249 llvm::SmallVector<MemInitTy*, 4> MemInitializers; 1250 1251 do { 1252 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1253 if (!MemInit.isInvalid()) 1254 MemInitializers.push_back(MemInit.get()); 1255 1256 if (Tok.is(tok::comma)) 1257 ConsumeToken(); 1258 else if (Tok.is(tok::l_brace)) 1259 break; 1260 else { 1261 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1262 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 1263 SkipUntil(tok::l_brace, true, true); 1264 break; 1265 } 1266 } while (true); 1267 1268 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 1269 MemInitializers.data(), MemInitializers.size()); 1270} 1271 1272/// ParseMemInitializer - Parse a C++ member initializer, which is 1273/// part of a constructor initializer that explicitly initializes one 1274/// member or base class (C++ [class.base.init]). See 1275/// ParseConstructorInitializer for an example. 1276/// 1277/// [C++] mem-initializer: 1278/// mem-initializer-id '(' expression-list[opt] ')' 1279/// 1280/// [C++] mem-initializer-id: 1281/// '::'[opt] nested-name-specifier[opt] class-name 1282/// identifier 1283Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) { 1284 // parse '::'[opt] nested-name-specifier[opt] 1285 CXXScopeSpec SS; 1286 ParseOptionalCXXScopeSpecifier(SS); 1287 TypeTy *TemplateTypeTy = 0; 1288 if (Tok.is(tok::annot_template_id)) { 1289 TemplateIdAnnotation *TemplateId 1290 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1291 if (TemplateId->Kind == TNK_Type_template) { 1292 AnnotateTemplateIdTokenAsType(&SS); 1293 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 1294 TemplateTypeTy = Tok.getAnnotationValue(); 1295 } 1296 // FIXME. May need to check for TNK_Dependent_template as well. 1297 } 1298 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 1299 Diag(Tok, diag::err_expected_member_or_base_name); 1300 return true; 1301 } 1302 1303 // Get the identifier. This may be a member name or a class name, 1304 // but we'll let the semantic analysis determine which it is. 1305 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 1306 SourceLocation IdLoc = ConsumeToken(); 1307 1308 // Parse the '('. 1309 if (Tok.isNot(tok::l_paren)) { 1310 Diag(Tok, diag::err_expected_lparen); 1311 return true; 1312 } 1313 SourceLocation LParenLoc = ConsumeParen(); 1314 1315 // Parse the optional expression-list. 1316 ExprVector ArgExprs(Actions); 1317 CommaLocsTy CommaLocs; 1318 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 1319 SkipUntil(tok::r_paren); 1320 return true; 1321 } 1322 1323 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1324 1325 return Actions.ActOnMemInitializer(ConstructorDecl, CurScope, SS, II, 1326 TemplateTypeTy, IdLoc, 1327 LParenLoc, ArgExprs.take(), 1328 ArgExprs.size(), CommaLocs.data(), 1329 RParenLoc); 1330} 1331 1332/// ParseExceptionSpecification - Parse a C++ exception-specification 1333/// (C++ [except.spec]). 1334/// 1335/// exception-specification: 1336/// 'throw' '(' type-id-list [opt] ')' 1337/// [MS] 'throw' '(' '...' ')' 1338/// 1339/// type-id-list: 1340/// type-id 1341/// type-id-list ',' type-id 1342/// 1343bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, 1344 llvm::SmallVector<TypeTy*, 2> 1345 &Exceptions, 1346 llvm::SmallVector<SourceRange, 2> 1347 &Ranges, 1348 bool &hasAnyExceptionSpec) { 1349 assert(Tok.is(tok::kw_throw) && "expected throw"); 1350 1351 SourceLocation ThrowLoc = ConsumeToken(); 1352 1353 if (!Tok.is(tok::l_paren)) { 1354 return Diag(Tok, diag::err_expected_lparen_after) << "throw"; 1355 } 1356 SourceLocation LParenLoc = ConsumeParen(); 1357 1358 // Parse throw(...), a Microsoft extension that means "this function 1359 // can throw anything". 1360 if (Tok.is(tok::ellipsis)) { 1361 hasAnyExceptionSpec = true; 1362 SourceLocation EllipsisLoc = ConsumeToken(); 1363 if (!getLang().Microsoft) 1364 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 1365 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1366 return false; 1367 } 1368 1369 // Parse the sequence of type-ids. 1370 SourceRange Range; 1371 while (Tok.isNot(tok::r_paren)) { 1372 TypeResult Res(ParseTypeName(&Range)); 1373 if (!Res.isInvalid()) { 1374 Exceptions.push_back(Res.get()); 1375 Ranges.push_back(Range); 1376 } 1377 if (Tok.is(tok::comma)) 1378 ConsumeToken(); 1379 else 1380 break; 1381 } 1382 1383 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1384 return false; 1385} 1386 1387/// \brief We have just started parsing the definition of a new class, 1388/// so push that class onto our stack of classes that is currently 1389/// being parsed. 1390void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool TopLevelClass) { 1391 assert((TopLevelClass || !ClassStack.empty()) && 1392 "Nested class without outer class"); 1393 ClassStack.push(new ParsingClass(ClassDecl, TopLevelClass)); 1394} 1395 1396/// \brief Deallocate the given parsed class and all of its nested 1397/// classes. 1398void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 1399 for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I) 1400 DeallocateParsedClasses(Class->NestedClasses[I]); 1401 delete Class; 1402} 1403 1404/// \brief Pop the top class of the stack of classes that are 1405/// currently being parsed. 1406/// 1407/// This routine should be called when we have finished parsing the 1408/// definition of a class, but have not yet popped the Scope 1409/// associated with the class's definition. 1410/// 1411/// \returns true if the class we've popped is a top-level class, 1412/// false otherwise. 1413void Parser::PopParsingClass() { 1414 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 1415 1416 ParsingClass *Victim = ClassStack.top(); 1417 ClassStack.pop(); 1418 if (Victim->TopLevelClass) { 1419 // Deallocate all of the nested classes of this class, 1420 // recursively: we don't need to keep any of this information. 1421 DeallocateParsedClasses(Victim); 1422 return; 1423 } 1424 assert(!ClassStack.empty() && "Missing top-level class?"); 1425 1426 if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && 1427 Victim->NestedClasses.empty()) { 1428 // The victim is a nested class, but we will not need to perform 1429 // any processing after the definition of this class since it has 1430 // no members whose handling was delayed. Therefore, we can just 1431 // remove this nested class. 1432 delete Victim; 1433 return; 1434 } 1435 1436 // This nested class has some members that will need to be processed 1437 // after the top-level class is completely defined. Therefore, add 1438 // it to the list of nested classes within its parent. 1439 assert(CurScope->isClassScope() && "Nested class outside of class scope?"); 1440 ClassStack.top()->NestedClasses.push_back(Victim); 1441 Victim->TemplateScope = CurScope->getParent()->isTemplateParamScope(); 1442} 1443