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