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