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