ParseDeclCXX.cpp revision 23c94dbb6631fecdb55ba401aa93722803d980c6
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(getCurScope()); 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 (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || 91 getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || 92 getCurScope()->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(getCurScope(), 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(getCurScope()); 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(getCurScope(), 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(getCurScope(), 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(getCurScope(), 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(getCurScope(), 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(getCurScope()); 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(getCurScope()); 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(getCurScope(), 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(getCurScope(), 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, getCurScope(), 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, getCurScope(), 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(getCurScope(), TagType); 613 ConsumeCodeCompletionToken(); 614 } 615 616 // C++03 [temp.explicit] 14.7.2/8: 617 // The usual access checking rules do not apply to names used to specify 618 // explicit instantiations. 619 // 620 // As an extension we do not perform access checking on the names used to 621 // specify explicit specializations either. This is important to allow 622 // specializing traits classes for private types. 623 bool SuppressingAccessChecks = false; 624 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || 625 TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) { 626 Actions.ActOnStartSuppressingAccessChecks(); 627 SuppressingAccessChecks = true; 628 } 629 630 AttributeList *AttrList = 0; 631 // If attributes exist after tag, parse them. 632 if (Tok.is(tok::kw___attribute)) 633 AttrList = ParseGNUAttributes(); 634 635 // If declspecs exist after tag, parse them. 636 if (Tok.is(tok::kw___declspec)) 637 AttrList = ParseMicrosoftDeclSpec(AttrList); 638 639 // If C++0x attributes exist here, parse them. 640 // FIXME: Are we consistent with the ordering of parsing of different 641 // styles of attributes? 642 if (isCXX0XAttributeSpecifier()) 643 AttrList = addAttributeLists(AttrList, ParseCXX0XAttributes().AttrList); 644 645 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_pod)) { 646 // GNU libstdc++ 4.2 uses __is_pod as the name of a struct template, but 647 // __is_pod is a keyword in GCC >= 4.3. Therefore, when we see the 648 // token sequence "struct __is_pod", make __is_pod into a normal 649 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 650 // properly. 651 Tok.getIdentifierInfo()->setTokenID(tok::identifier); 652 Tok.setKind(tok::identifier); 653 } 654 655 if (TagType == DeclSpec::TST_struct && Tok.is(tok::kw___is_empty)) { 656 // GNU libstdc++ 4.2 uses __is_empty as the name of a struct template, but 657 // __is_empty is a keyword in GCC >= 4.3. Therefore, when we see the 658 // token sequence "struct __is_empty", make __is_empty into a normal 659 // identifier rather than a keyword, to allow libstdc++ 4.2 to work 660 // properly. 661 Tok.getIdentifierInfo()->setTokenID(tok::identifier); 662 Tok.setKind(tok::identifier); 663 } 664 665 // Parse the (optional) nested-name-specifier. 666 CXXScopeSpec &SS = DS.getTypeSpecScope(); 667 if (getLang().CPlusPlus) { 668 // "FOO : BAR" is not a potential typo for "FOO::BAR". 669 ColonProtectionRAIIObject X(*this); 670 671 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, true); 672 if (SS.isSet()) 673 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) 674 Diag(Tok, diag::err_expected_ident); 675 } 676 677 TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; 678 679 // Parse the (optional) class name or simple-template-id. 680 IdentifierInfo *Name = 0; 681 SourceLocation NameLoc; 682 TemplateIdAnnotation *TemplateId = 0; 683 if (Tok.is(tok::identifier)) { 684 Name = Tok.getIdentifierInfo(); 685 NameLoc = ConsumeToken(); 686 687 if (Tok.is(tok::less) && getLang().CPlusPlus) { 688 // The name was supposed to refer to a template, but didn't. 689 // Eat the template argument list and try to continue parsing this as 690 // a class (or template thereof). 691 TemplateArgList TemplateArgs; 692 SourceLocation LAngleLoc, RAngleLoc; 693 if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, &SS, 694 true, LAngleLoc, 695 TemplateArgs, RAngleLoc)) { 696 // We couldn't parse the template argument list at all, so don't 697 // try to give any location information for the list. 698 LAngleLoc = RAngleLoc = SourceLocation(); 699 } 700 701 Diag(NameLoc, diag::err_explicit_spec_non_template) 702 << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) 703 << (TagType == DeclSpec::TST_class? 0 704 : TagType == DeclSpec::TST_struct? 1 705 : 2) 706 << Name 707 << SourceRange(LAngleLoc, RAngleLoc); 708 709 // Strip off the last template parameter list if it was empty, since 710 // we've removed its template argument list. 711 if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { 712 if (TemplateParams && TemplateParams->size() > 1) { 713 TemplateParams->pop_back(); 714 } else { 715 TemplateParams = 0; 716 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 717 = ParsedTemplateInfo::NonTemplate; 718 } 719 } else if (TemplateInfo.Kind 720 == ParsedTemplateInfo::ExplicitInstantiation) { 721 // Pretend this is just a forward declaration. 722 TemplateParams = 0; 723 const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind 724 = ParsedTemplateInfo::NonTemplate; 725 const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc 726 = SourceLocation(); 727 const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc 728 = SourceLocation(); 729 } 730 } 731 } else if (Tok.is(tok::annot_template_id)) { 732 TemplateId = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 733 NameLoc = ConsumeToken(); 734 735 if (TemplateId->Kind != TNK_Type_template) { 736 // The template-name in the simple-template-id refers to 737 // something other than a class template. Give an appropriate 738 // error message and skip to the ';'. 739 SourceRange Range(NameLoc); 740 if (SS.isNotEmpty()) 741 Range.setBegin(SS.getBeginLoc()); 742 743 Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) 744 << Name << static_cast<int>(TemplateId->Kind) << Range; 745 746 DS.SetTypeSpecError(); 747 SkipUntil(tok::semi, false, true); 748 TemplateId->Destroy(); 749 if (SuppressingAccessChecks) 750 Actions.ActOnStopSuppressingAccessChecks(); 751 752 return; 753 } 754 } 755 756 // As soon as we're finished parsing the class's template-id, turn access 757 // checking back on. 758 if (SuppressingAccessChecks) 759 Actions.ActOnStopSuppressingAccessChecks(); 760 761 // There are four options here. If we have 'struct foo;', then this 762 // is either a forward declaration or a friend declaration, which 763 // have to be treated differently. If we have 'struct foo {...' or 764 // 'struct foo :...' then this is a definition. Otherwise we have 765 // something like 'struct foo xyz', a reference. 766 // However, in some contexts, things look like declarations but are just 767 // references, e.g. 768 // new struct s; 769 // or 770 // &T::operator struct s; 771 // For these, SuppressDeclarations is true. 772 Action::TagUseKind TUK; 773 if (SuppressDeclarations) 774 TUK = Action::TUK_Reference; 775 else if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))){ 776 if (DS.isFriendSpecified()) { 777 // C++ [class.friend]p2: 778 // A class shall not be defined in a friend declaration. 779 Diag(Tok.getLocation(), diag::err_friend_decl_defines_class) 780 << SourceRange(DS.getFriendSpecLoc()); 781 782 // Skip everything up to the semicolon, so that this looks like a proper 783 // friend class (or template thereof) declaration. 784 SkipUntil(tok::semi, true, true); 785 TUK = Action::TUK_Friend; 786 } else { 787 // Okay, this is a class definition. 788 TUK = Action::TUK_Definition; 789 } 790 } else if (Tok.is(tok::semi)) 791 TUK = DS.isFriendSpecified() ? Action::TUK_Friend : Action::TUK_Declaration; 792 else 793 TUK = Action::TUK_Reference; 794 795 if (!Name && !TemplateId && TUK != Action::TUK_Definition) { 796 // We have a declaration or reference to an anonymous class. 797 Diag(StartLoc, diag::err_anon_type_definition) 798 << DeclSpec::getSpecifierName(TagType); 799 800 SkipUntil(tok::comma, true); 801 802 if (TemplateId) 803 TemplateId->Destroy(); 804 return; 805 } 806 807 // Create the tag portion of the class or class template. 808 Action::DeclResult TagOrTempResult = true; // invalid 809 Action::TypeResult TypeResult = true; // invalid 810 811 bool Owned = false; 812 if (TemplateId) { 813 // Explicit specialization, class template partial specialization, 814 // or explicit instantiation. 815 ASTTemplateArgsPtr TemplateArgsPtr(Actions, 816 TemplateId->getTemplateArgs(), 817 TemplateId->NumArgs); 818 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 819 TUK == Action::TUK_Declaration) { 820 // This is an explicit instantiation of a class template. 821 TagOrTempResult 822 = Actions.ActOnExplicitInstantiation(getCurScope(), 823 TemplateInfo.ExternLoc, 824 TemplateInfo.TemplateLoc, 825 TagType, 826 StartLoc, 827 SS, 828 TemplateTy::make(TemplateId->Template), 829 TemplateId->TemplateNameLoc, 830 TemplateId->LAngleLoc, 831 TemplateArgsPtr, 832 TemplateId->RAngleLoc, 833 AttrList); 834 835 // Friend template-ids are treated as references unless 836 // they have template headers, in which case they're ill-formed 837 // (FIXME: "template <class T> friend class A<T>::B<int>;"). 838 // We diagnose this error in ActOnClassTemplateSpecialization. 839 } else if (TUK == Action::TUK_Reference || 840 (TUK == Action::TUK_Friend && 841 TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { 842 TypeResult 843 = Actions.ActOnTemplateIdType(TemplateTy::make(TemplateId->Template), 844 TemplateId->TemplateNameLoc, 845 TemplateId->LAngleLoc, 846 TemplateArgsPtr, 847 TemplateId->RAngleLoc); 848 849 TypeResult = Actions.ActOnTagTemplateIdType(TypeResult, TUK, 850 TagType, StartLoc); 851 } else { 852 // This is an explicit specialization or a class template 853 // partial specialization. 854 TemplateParameterLists FakedParamLists; 855 856 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { 857 // This looks like an explicit instantiation, because we have 858 // something like 859 // 860 // template class Foo<X> 861 // 862 // but it actually has a definition. Most likely, this was 863 // meant to be an explicit specialization, but the user forgot 864 // the '<>' after 'template'. 865 assert(TUK == Action::TUK_Definition && "Expected a definition here"); 866 867 SourceLocation LAngleLoc 868 = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); 869 Diag(TemplateId->TemplateNameLoc, 870 diag::err_explicit_instantiation_with_definition) 871 << SourceRange(TemplateInfo.TemplateLoc) 872 << FixItHint::CreateInsertion(LAngleLoc, "<>"); 873 874 // Create a fake template parameter list that contains only 875 // "template<>", so that we treat this construct as a class 876 // template specialization. 877 FakedParamLists.push_back( 878 Actions.ActOnTemplateParameterList(0, SourceLocation(), 879 TemplateInfo.TemplateLoc, 880 LAngleLoc, 881 0, 0, 882 LAngleLoc)); 883 TemplateParams = &FakedParamLists; 884 } 885 886 // Build the class template specialization. 887 TagOrTempResult 888 = Actions.ActOnClassTemplateSpecialization(getCurScope(), TagType, TUK, 889 StartLoc, SS, 890 TemplateTy::make(TemplateId->Template), 891 TemplateId->TemplateNameLoc, 892 TemplateId->LAngleLoc, 893 TemplateArgsPtr, 894 TemplateId->RAngleLoc, 895 AttrList, 896 Action::MultiTemplateParamsArg(Actions, 897 TemplateParams? &(*TemplateParams)[0] : 0, 898 TemplateParams? TemplateParams->size() : 0)); 899 } 900 TemplateId->Destroy(); 901 } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 902 TUK == Action::TUK_Declaration) { 903 // Explicit instantiation of a member of a class template 904 // specialization, e.g., 905 // 906 // template struct Outer<int>::Inner; 907 // 908 TagOrTempResult 909 = Actions.ActOnExplicitInstantiation(getCurScope(), 910 TemplateInfo.ExternLoc, 911 TemplateInfo.TemplateLoc, 912 TagType, StartLoc, SS, Name, 913 NameLoc, AttrList); 914 } else { 915 if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && 916 TUK == Action::TUK_Definition) { 917 // FIXME: Diagnose this particular error. 918 } 919 920 bool IsDependent = false; 921 922 // Declaration or definition of a class type 923 TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, SS, 924 Name, NameLoc, AttrList, AS, 925 Action::MultiTemplateParamsArg(Actions, 926 TemplateParams? &(*TemplateParams)[0] : 0, 927 TemplateParams? TemplateParams->size() : 0), 928 Owned, IsDependent); 929 930 // If ActOnTag said the type was dependent, try again with the 931 // less common call. 932 if (IsDependent) 933 TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, 934 SS, Name, StartLoc, NameLoc); 935 } 936 937 // If there is a body, parse it and inform the actions module. 938 if (TUK == Action::TUK_Definition) { 939 assert(Tok.is(tok::l_brace) || 940 (getLang().CPlusPlus && Tok.is(tok::colon))); 941 if (getLang().CPlusPlus) 942 ParseCXXMemberSpecification(StartLoc, TagType, TagOrTempResult.get()); 943 else 944 ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); 945 } 946 947 void *Result; 948 if (!TypeResult.isInvalid()) { 949 TagType = DeclSpec::TST_typename; 950 Result = TypeResult.get(); 951 Owned = false; 952 } else if (!TagOrTempResult.isInvalid()) { 953 Result = TagOrTempResult.get().getAs<void>(); 954 } else { 955 DS.SetTypeSpecError(); 956 return; 957 } 958 959 const char *PrevSpec = 0; 960 unsigned DiagID; 961 962 // FIXME: The DeclSpec should keep the locations of both the keyword and the 963 // name (if there is one). 964 SourceLocation TSTLoc = NameLoc.isValid()? NameLoc : StartLoc; 965 966 if (DS.SetTypeSpecType(TagType, TSTLoc, PrevSpec, DiagID, 967 Result, Owned)) 968 Diag(StartLoc, DiagID) << PrevSpec; 969 970 // At this point, we've successfully parsed a class-specifier in 'definition' 971 // form (e.g. "struct foo { int x; }". While we could just return here, we're 972 // going to look at what comes after it to improve error recovery. If an 973 // impossible token occurs next, we assume that the programmer forgot a ; at 974 // the end of the declaration and recover that way. 975 // 976 // This switch enumerates the valid "follow" set for definition. 977 if (TUK == Action::TUK_Definition) { 978 bool ExpectedSemi = true; 979 switch (Tok.getKind()) { 980 default: break; 981 case tok::semi: // struct foo {...} ; 982 case tok::star: // struct foo {...} * P; 983 case tok::amp: // struct foo {...} & R = ... 984 case tok::identifier: // struct foo {...} V ; 985 case tok::r_paren: //(struct foo {...} ) {4} 986 case tok::annot_cxxscope: // struct foo {...} a:: b; 987 case tok::annot_typename: // struct foo {...} a ::b; 988 case tok::annot_template_id: // struct foo {...} a<int> ::b; 989 case tok::l_paren: // struct foo {...} ( x); 990 case tok::comma: // __builtin_offsetof(struct foo{...} , 991 ExpectedSemi = false; 992 break; 993 // Type qualifiers 994 case tok::kw_const: // struct foo {...} const x; 995 case tok::kw_volatile: // struct foo {...} volatile x; 996 case tok::kw_restrict: // struct foo {...} restrict x; 997 case tok::kw_inline: // struct foo {...} inline foo() {}; 998 // Storage-class specifiers 999 case tok::kw_static: // struct foo {...} static x; 1000 case tok::kw_extern: // struct foo {...} extern x; 1001 case tok::kw_typedef: // struct foo {...} typedef x; 1002 case tok::kw_register: // struct foo {...} register x; 1003 case tok::kw_auto: // struct foo {...} auto x; 1004 case tok::kw_mutable: // struct foo {...} mutable x; 1005 // As shown above, type qualifiers and storage class specifiers absolutely 1006 // can occur after class specifiers according to the grammar. However, 1007 // almost noone actually writes code like this. If we see one of these, 1008 // it is much more likely that someone missed a semi colon and the 1009 // type/storage class specifier we're seeing is part of the *next* 1010 // intended declaration, as in: 1011 // 1012 // struct foo { ... } 1013 // typedef int X; 1014 // 1015 // We'd really like to emit a missing semicolon error instead of emitting 1016 // an error on the 'int' saying that you can't have two type specifiers in 1017 // the same declaration of X. Because of this, we look ahead past this 1018 // token to see if it's a type specifier. If so, we know the code is 1019 // otherwise invalid, so we can produce the expected semi error. 1020 if (!isKnownToBeTypeSpecifier(NextToken())) 1021 ExpectedSemi = false; 1022 break; 1023 1024 case tok::r_brace: // struct bar { struct foo {...} } 1025 // Missing ';' at end of struct is accepted as an extension in C mode. 1026 if (!getLang().CPlusPlus) 1027 ExpectedSemi = false; 1028 break; 1029 } 1030 1031 if (ExpectedSemi) { 1032 ExpectAndConsume(tok::semi, diag::err_expected_semi_after_tagdecl, 1033 TagType == DeclSpec::TST_class ? "class" 1034 : TagType == DeclSpec::TST_struct? "struct" : "union"); 1035 // Push this token back into the preprocessor and change our current token 1036 // to ';' so that the rest of the code recovers as though there were an 1037 // ';' after the definition. 1038 PP.EnterToken(Tok); 1039 Tok.setKind(tok::semi); 1040 } 1041 } 1042} 1043 1044/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 1045/// 1046/// base-clause : [C++ class.derived] 1047/// ':' base-specifier-list 1048/// base-specifier-list: 1049/// base-specifier '...'[opt] 1050/// base-specifier-list ',' base-specifier '...'[opt] 1051void Parser::ParseBaseClause(DeclPtrTy ClassDecl) { 1052 assert(Tok.is(tok::colon) && "Not a base clause"); 1053 ConsumeToken(); 1054 1055 // Build up an array of parsed base specifiers. 1056 llvm::SmallVector<BaseTy *, 8> BaseInfo; 1057 1058 while (true) { 1059 // Parse a base-specifier. 1060 BaseResult Result = ParseBaseSpecifier(ClassDecl); 1061 if (Result.isInvalid()) { 1062 // Skip the rest of this base specifier, up until the comma or 1063 // opening brace. 1064 SkipUntil(tok::comma, tok::l_brace, true, true); 1065 } else { 1066 // Add this to our array of base specifiers. 1067 BaseInfo.push_back(Result.get()); 1068 } 1069 1070 // If the next token is a comma, consume it and keep reading 1071 // base-specifiers. 1072 if (Tok.isNot(tok::comma)) break; 1073 1074 // Consume the comma. 1075 ConsumeToken(); 1076 } 1077 1078 // Attach the base specifiers 1079 Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); 1080} 1081 1082/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 1083/// one entry in the base class list of a class specifier, for example: 1084/// class foo : public bar, virtual private baz { 1085/// 'public bar' and 'virtual private baz' are each base-specifiers. 1086/// 1087/// base-specifier: [C++ class.derived] 1088/// ::[opt] nested-name-specifier[opt] class-name 1089/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 1090/// class-name 1091/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 1092/// class-name 1093Parser::BaseResult Parser::ParseBaseSpecifier(DeclPtrTy ClassDecl) { 1094 bool IsVirtual = false; 1095 SourceLocation StartLoc = Tok.getLocation(); 1096 1097 // Parse the 'virtual' keyword. 1098 if (Tok.is(tok::kw_virtual)) { 1099 ConsumeToken(); 1100 IsVirtual = true; 1101 } 1102 1103 // Parse an (optional) access specifier. 1104 AccessSpecifier Access = getAccessSpecifierIfPresent(); 1105 if (Access != AS_none) 1106 ConsumeToken(); 1107 1108 // Parse the 'virtual' keyword (again!), in case it came after the 1109 // access specifier. 1110 if (Tok.is(tok::kw_virtual)) { 1111 SourceLocation VirtualLoc = ConsumeToken(); 1112 if (IsVirtual) { 1113 // Complain about duplicate 'virtual' 1114 Diag(VirtualLoc, diag::err_dup_virtual) 1115 << FixItHint::CreateRemoval(VirtualLoc); 1116 } 1117 1118 IsVirtual = true; 1119 } 1120 1121 // Parse optional '::' and optional nested-name-specifier. 1122 CXXScopeSpec SS; 1123 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, 1124 /*EnteringContext=*/false); 1125 1126 // The location of the base class itself. 1127 SourceLocation BaseLoc = Tok.getLocation(); 1128 1129 // Parse the class-name. 1130 SourceLocation EndLocation; 1131 TypeResult BaseType = ParseClassName(EndLocation, &SS); 1132 if (BaseType.isInvalid()) 1133 return true; 1134 1135 // Find the complete source range for the base-specifier. 1136 SourceRange Range(StartLoc, EndLocation); 1137 1138 // Notify semantic analysis that we have parsed a complete 1139 // base-specifier. 1140 return Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, 1141 BaseType.get(), BaseLoc); 1142} 1143 1144/// getAccessSpecifierIfPresent - Determine whether the next token is 1145/// a C++ access-specifier. 1146/// 1147/// access-specifier: [C++ class.derived] 1148/// 'private' 1149/// 'protected' 1150/// 'public' 1151AccessSpecifier Parser::getAccessSpecifierIfPresent() const { 1152 switch (Tok.getKind()) { 1153 default: return AS_none; 1154 case tok::kw_private: return AS_private; 1155 case tok::kw_protected: return AS_protected; 1156 case tok::kw_public: return AS_public; 1157 } 1158} 1159 1160void Parser::HandleMemberFunctionDefaultArgs(Declarator& DeclaratorInfo, 1161 DeclPtrTy ThisDecl) { 1162 // We just declared a member function. If this member function 1163 // has any default arguments, we'll need to parse them later. 1164 LateParsedMethodDeclaration *LateMethod = 0; 1165 DeclaratorChunk::FunctionTypeInfo &FTI 1166 = DeclaratorInfo.getTypeObject(0).Fun; 1167 for (unsigned ParamIdx = 0; ParamIdx < FTI.NumArgs; ++ParamIdx) { 1168 if (LateMethod || FTI.ArgInfo[ParamIdx].DefaultArgTokens) { 1169 if (!LateMethod) { 1170 // Push this method onto the stack of late-parsed method 1171 // declarations. 1172 getCurrentClass().MethodDecls.push_back( 1173 LateParsedMethodDeclaration(ThisDecl)); 1174 LateMethod = &getCurrentClass().MethodDecls.back(); 1175 LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); 1176 1177 // Add all of the parameters prior to this one (they don't 1178 // have default arguments). 1179 LateMethod->DefaultArgs.reserve(FTI.NumArgs); 1180 for (unsigned I = 0; I < ParamIdx; ++I) 1181 LateMethod->DefaultArgs.push_back( 1182 LateParsedDefaultArgument(FTI.ArgInfo[I].Param)); 1183 } 1184 1185 // Add this parameter to the list of parameters (it or may 1186 // not have a default argument). 1187 LateMethod->DefaultArgs.push_back( 1188 LateParsedDefaultArgument(FTI.ArgInfo[ParamIdx].Param, 1189 FTI.ArgInfo[ParamIdx].DefaultArgTokens)); 1190 } 1191 } 1192} 1193 1194/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 1195/// 1196/// member-declaration: 1197/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 1198/// function-definition ';'[opt] 1199/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 1200/// using-declaration [TODO] 1201/// [C++0x] static_assert-declaration 1202/// template-declaration 1203/// [GNU] '__extension__' member-declaration 1204/// 1205/// member-declarator-list: 1206/// member-declarator 1207/// member-declarator-list ',' member-declarator 1208/// 1209/// member-declarator: 1210/// declarator pure-specifier[opt] 1211/// declarator constant-initializer[opt] 1212/// identifier[opt] ':' constant-expression 1213/// 1214/// pure-specifier: 1215/// '= 0' 1216/// 1217/// constant-initializer: 1218/// '=' constant-expression 1219/// 1220void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, 1221 const ParsedTemplateInfo &TemplateInfo) { 1222 // Access declarations. 1223 if (!TemplateInfo.Kind && 1224 (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) && 1225 !TryAnnotateCXXScopeToken() && 1226 Tok.is(tok::annot_cxxscope)) { 1227 bool isAccessDecl = false; 1228 if (NextToken().is(tok::identifier)) 1229 isAccessDecl = GetLookAheadToken(2).is(tok::semi); 1230 else 1231 isAccessDecl = NextToken().is(tok::kw_operator); 1232 1233 if (isAccessDecl) { 1234 // Collect the scope specifier token we annotated earlier. 1235 CXXScopeSpec SS; 1236 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType*/ 0, false); 1237 1238 // Try to parse an unqualified-id. 1239 UnqualifiedId Name; 1240 if (ParseUnqualifiedId(SS, false, true, true, /*ObjectType*/ 0, Name)) { 1241 SkipUntil(tok::semi); 1242 return; 1243 } 1244 1245 // TODO: recover from mistakenly-qualified operator declarations. 1246 if (ExpectAndConsume(tok::semi, 1247 diag::err_expected_semi_after, 1248 "access declaration", 1249 tok::semi)) 1250 return; 1251 1252 Actions.ActOnUsingDeclaration(getCurScope(), AS, 1253 false, SourceLocation(), 1254 SS, Name, 1255 /* AttrList */ 0, 1256 /* IsTypeName */ false, 1257 SourceLocation()); 1258 return; 1259 } 1260 } 1261 1262 // static_assert-declaration 1263 if (Tok.is(tok::kw_static_assert)) { 1264 // FIXME: Check for templates 1265 SourceLocation DeclEnd; 1266 ParseStaticAssertDeclaration(DeclEnd); 1267 return; 1268 } 1269 1270 if (Tok.is(tok::kw_template)) { 1271 assert(!TemplateInfo.TemplateParams && 1272 "Nested template improperly parsed?"); 1273 SourceLocation DeclEnd; 1274 ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, 1275 AS); 1276 return; 1277 } 1278 1279 // Handle: member-declaration ::= '__extension__' member-declaration 1280 if (Tok.is(tok::kw___extension__)) { 1281 // __extension__ silences extension warnings in the subexpression. 1282 ExtensionRAIIObject O(Diags); // Use RAII to do this. 1283 ConsumeToken(); 1284 return ParseCXXClassMemberDeclaration(AS, TemplateInfo); 1285 } 1286 1287 // Don't parse FOO:BAR as if it were a typo for FOO::BAR, in this context it 1288 // is a bitfield. 1289 ColonProtectionRAIIObject X(*this); 1290 1291 CXX0XAttributeList AttrList; 1292 // Optional C++0x attribute-specifier 1293 if (getLang().CPlusPlus0x && isCXX0XAttributeSpecifier()) 1294 AttrList = ParseCXX0XAttributes(); 1295 1296 if (Tok.is(tok::kw_using)) { 1297 // FIXME: Check for template aliases 1298 1299 if (AttrList.HasAttr) 1300 Diag(AttrList.Range.getBegin(), diag::err_attributes_not_allowed) 1301 << AttrList.Range; 1302 1303 // Eat 'using'. 1304 SourceLocation UsingLoc = ConsumeToken(); 1305 1306 if (Tok.is(tok::kw_namespace)) { 1307 Diag(UsingLoc, diag::err_using_namespace_in_class); 1308 SkipUntil(tok::semi, true, true); 1309 } else { 1310 SourceLocation DeclEnd; 1311 // Otherwise, it must be using-declaration. 1312 ParseUsingDeclaration(Declarator::MemberContext, UsingLoc, DeclEnd, AS); 1313 } 1314 return; 1315 } 1316 1317 SourceLocation DSStart = Tok.getLocation(); 1318 // decl-specifier-seq: 1319 // Parse the common declaration-specifiers piece. 1320 ParsingDeclSpec DS(*this); 1321 DS.AddAttributes(AttrList.AttrList); 1322 ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class); 1323 1324 Action::MultiTemplateParamsArg TemplateParams(Actions, 1325 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : 0, 1326 TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); 1327 1328 if (Tok.is(tok::semi)) { 1329 ConsumeToken(); 1330 Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); 1331 return; 1332 } 1333 1334 ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); 1335 1336 if (Tok.isNot(tok::colon)) { 1337 // Don't parse FOO:BAR as if it were a typo for FOO::BAR. 1338 ColonProtectionRAIIObject X(*this); 1339 1340 // Parse the first declarator. 1341 ParseDeclarator(DeclaratorInfo); 1342 // Error parsing the declarator? 1343 if (!DeclaratorInfo.hasName()) { 1344 // If so, skip until the semi-colon or a }. 1345 SkipUntil(tok::r_brace, true); 1346 if (Tok.is(tok::semi)) 1347 ConsumeToken(); 1348 return; 1349 } 1350 1351 // If attributes exist after the declarator, but before an '{', parse them. 1352 if (Tok.is(tok::kw___attribute)) { 1353 SourceLocation Loc; 1354 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1355 DeclaratorInfo.AddAttributes(AttrList, Loc); 1356 } 1357 1358 // function-definition: 1359 if (Tok.is(tok::l_brace) 1360 || (DeclaratorInfo.isFunctionDeclarator() && 1361 (Tok.is(tok::colon) || Tok.is(tok::kw_try)))) { 1362 if (!DeclaratorInfo.isFunctionDeclarator()) { 1363 Diag(Tok, diag::err_func_def_no_params); 1364 ConsumeBrace(); 1365 SkipUntil(tok::r_brace, true); 1366 return; 1367 } 1368 1369 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 1370 Diag(Tok, diag::err_function_declared_typedef); 1371 // This recovery skips the entire function body. It would be nice 1372 // to simply call ParseCXXInlineMethodDef() below, however Sema 1373 // assumes the declarator represents a function, not a typedef. 1374 ConsumeBrace(); 1375 SkipUntil(tok::r_brace, true); 1376 return; 1377 } 1378 1379 ParseCXXInlineMethodDef(AS, DeclaratorInfo, TemplateInfo); 1380 return; 1381 } 1382 } 1383 1384 // member-declarator-list: 1385 // member-declarator 1386 // member-declarator-list ',' member-declarator 1387 1388 llvm::SmallVector<DeclPtrTy, 8> DeclsInGroup; 1389 OwningExprResult BitfieldSize(Actions); 1390 OwningExprResult Init(Actions); 1391 bool Deleted = false; 1392 1393 while (1) { 1394 // member-declarator: 1395 // declarator pure-specifier[opt] 1396 // declarator constant-initializer[opt] 1397 // identifier[opt] ':' constant-expression 1398 if (Tok.is(tok::colon)) { 1399 ConsumeToken(); 1400 BitfieldSize = ParseConstantExpression(); 1401 if (BitfieldSize.isInvalid()) 1402 SkipUntil(tok::comma, true, true); 1403 } 1404 1405 // pure-specifier: 1406 // '= 0' 1407 // 1408 // constant-initializer: 1409 // '=' constant-expression 1410 // 1411 // defaulted/deleted function-definition: 1412 // '=' 'default' [TODO] 1413 // '=' 'delete' 1414 if (Tok.is(tok::equal)) { 1415 ConsumeToken(); 1416 if (getLang().CPlusPlus0x && Tok.is(tok::kw_delete)) { 1417 ConsumeToken(); 1418 Deleted = true; 1419 } else { 1420 Init = ParseInitializer(); 1421 if (Init.isInvalid()) 1422 SkipUntil(tok::comma, true, true); 1423 } 1424 } 1425 1426 // If a simple-asm-expr is present, parse it. 1427 if (Tok.is(tok::kw_asm)) { 1428 SourceLocation Loc; 1429 OwningExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1430 if (AsmLabel.isInvalid()) 1431 SkipUntil(tok::comma, true, true); 1432 1433 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1434 DeclaratorInfo.SetRangeEnd(Loc); 1435 } 1436 1437 // If attributes exist after the declarator, parse them. 1438 if (Tok.is(tok::kw___attribute)) { 1439 SourceLocation Loc; 1440 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1441 DeclaratorInfo.AddAttributes(AttrList, Loc); 1442 } 1443 1444 // NOTE: If Sema is the Action module and declarator is an instance field, 1445 // this call will *not* return the created decl; It will return null. 1446 // See Sema::ActOnCXXMemberDeclarator for details. 1447 1448 DeclPtrTy ThisDecl; 1449 if (DS.isFriendSpecified()) { 1450 // TODO: handle initializers, bitfields, 'delete' 1451 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 1452 /*IsDefinition*/ false, 1453 move(TemplateParams)); 1454 } else { 1455 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 1456 DeclaratorInfo, 1457 move(TemplateParams), 1458 BitfieldSize.release(), 1459 Init.release(), 1460 /*IsDefinition*/Deleted, 1461 Deleted); 1462 } 1463 if (ThisDecl) 1464 DeclsInGroup.push_back(ThisDecl); 1465 1466 if (DeclaratorInfo.isFunctionDeclarator() && 1467 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1468 != DeclSpec::SCS_typedef) { 1469 HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); 1470 } 1471 1472 DeclaratorInfo.complete(ThisDecl); 1473 1474 // If we don't have a comma, it is either the end of the list (a ';') 1475 // or an error, bail out. 1476 if (Tok.isNot(tok::comma)) 1477 break; 1478 1479 // Consume the comma. 1480 ConsumeToken(); 1481 1482 // Parse the next declarator. 1483 DeclaratorInfo.clear(); 1484 BitfieldSize = 0; 1485 Init = 0; 1486 Deleted = false; 1487 1488 // Attributes are only allowed on the second declarator. 1489 if (Tok.is(tok::kw___attribute)) { 1490 SourceLocation Loc; 1491 AttributeList *AttrList = ParseGNUAttributes(&Loc); 1492 DeclaratorInfo.AddAttributes(AttrList, Loc); 1493 } 1494 1495 if (Tok.isNot(tok::colon)) 1496 ParseDeclarator(DeclaratorInfo); 1497 } 1498 1499 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 1500 // Skip to end of block or statement. 1501 SkipUntil(tok::r_brace, true, true); 1502 // If we stopped at a ';', eat it. 1503 if (Tok.is(tok::semi)) ConsumeToken(); 1504 return; 1505 } 1506 1507 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 1508 DeclsInGroup.size()); 1509} 1510 1511/// ParseCXXMemberSpecification - Parse the class definition. 1512/// 1513/// member-specification: 1514/// member-declaration member-specification[opt] 1515/// access-specifier ':' member-specification[opt] 1516/// 1517void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1518 unsigned TagType, DeclPtrTy TagDecl) { 1519 assert((TagType == DeclSpec::TST_struct || 1520 TagType == DeclSpec::TST_union || 1521 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1522 1523 PrettyStackTraceActionsDecl CrashInfo(TagDecl, RecordLoc, Actions, 1524 PP.getSourceManager(), 1525 "parsing struct/union/class body"); 1526 1527 // Determine whether this is a non-nested class. Note that local 1528 // classes are *not* considered to be nested classes. 1529 bool NonNestedClass = true; 1530 if (!ClassStack.empty()) { 1531 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 1532 if (S->isClassScope()) { 1533 // We're inside a class scope, so this is a nested class. 1534 NonNestedClass = false; 1535 break; 1536 } 1537 1538 if ((S->getFlags() & Scope::FnScope)) { 1539 // If we're in a function or function template declared in the 1540 // body of a class, then this is a local class rather than a 1541 // nested class. 1542 const Scope *Parent = S->getParent(); 1543 if (Parent->isTemplateParamScope()) 1544 Parent = Parent->getParent(); 1545 if (Parent->isClassScope()) 1546 break; 1547 } 1548 } 1549 } 1550 1551 // Enter a scope for the class. 1552 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1553 1554 // Note that we are parsing a new (potentially-nested) class definition. 1555 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 1556 1557 if (TagDecl) 1558 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1559 1560 if (Tok.is(tok::colon)) { 1561 ParseBaseClause(TagDecl); 1562 1563 if (!Tok.is(tok::l_brace)) { 1564 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 1565 1566 if (TagDecl) 1567 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 1568 return; 1569 } 1570 } 1571 1572 assert(Tok.is(tok::l_brace)); 1573 1574 SourceLocation LBraceLoc = ConsumeBrace(); 1575 1576 if (TagDecl) 1577 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, LBraceLoc); 1578 1579 // C++ 11p3: Members of a class defined with the keyword class are private 1580 // by default. Members of a class defined with the keywords struct or union 1581 // are public by default. 1582 AccessSpecifier CurAS; 1583 if (TagType == DeclSpec::TST_class) 1584 CurAS = AS_private; 1585 else 1586 CurAS = AS_public; 1587 1588 SourceLocation RBraceLoc; 1589 if (TagDecl) { 1590 // While we still have something to read, read the member-declarations. 1591 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1592 // Each iteration of this loop reads one member-declaration. 1593 1594 // Check for extraneous top-level semicolon. 1595 if (Tok.is(tok::semi)) { 1596 Diag(Tok, diag::ext_extra_struct_semi) 1597 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1598 << FixItHint::CreateRemoval(Tok.getLocation()); 1599 ConsumeToken(); 1600 continue; 1601 } 1602 1603 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1604 if (AS != AS_none) { 1605 // Current token is a C++ access specifier. 1606 CurAS = AS; 1607 SourceLocation ASLoc = Tok.getLocation(); 1608 ConsumeToken(); 1609 if (Tok.is(tok::colon)) 1610 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 1611 else 1612 Diag(Tok, diag::err_expected_colon); 1613 ConsumeToken(); 1614 continue; 1615 } 1616 1617 // FIXME: Make sure we don't have a template here. 1618 1619 // Parse all the comma separated declarators. 1620 ParseCXXClassMemberDeclaration(CurAS); 1621 } 1622 1623 RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1624 } else { 1625 SkipUntil(tok::r_brace, false, false); 1626 } 1627 1628 // If attributes exist after class contents, parse them. 1629 llvm::OwningPtr<AttributeList> AttrList; 1630 if (Tok.is(tok::kw___attribute)) 1631 AttrList.reset(ParseGNUAttributes()); 1632 1633 if (TagDecl) 1634 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 1635 LBraceLoc, RBraceLoc, 1636 AttrList.get()); 1637 1638 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1639 // complete within function bodies, default arguments, 1640 // exception-specifications, and constructor ctor-initializers (including 1641 // such things in nested classes). 1642 // 1643 // FIXME: Only function bodies and constructor ctor-initializers are 1644 // parsed correctly, fix the rest. 1645 if (TagDecl && NonNestedClass) { 1646 // We are not inside a nested class. This class and its nested classes 1647 // are complete and we can parse the delayed portions of method 1648 // declarations and the lexed inline method definitions. 1649 SourceLocation SavedPrevTokLocation = PrevTokLocation; 1650 ParseLexedMethodDeclarations(getCurrentClass()); 1651 ParseLexedMethodDefs(getCurrentClass()); 1652 PrevTokLocation = SavedPrevTokLocation; 1653 } 1654 1655 if (TagDecl) 1656 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1657 1658 // Leave the class scope. 1659 ParsingDef.Pop(); 1660 ClassScope.Exit(); 1661} 1662 1663/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1664/// which explicitly initializes the members or base classes of a 1665/// class (C++ [class.base.init]). For example, the three initializers 1666/// after the ':' in the Derived constructor below: 1667/// 1668/// @code 1669/// class Base { }; 1670/// class Derived : Base { 1671/// int x; 1672/// float f; 1673/// public: 1674/// Derived(float f) : Base(), x(17), f(f) { } 1675/// }; 1676/// @endcode 1677/// 1678/// [C++] ctor-initializer: 1679/// ':' mem-initializer-list 1680/// 1681/// [C++] mem-initializer-list: 1682/// mem-initializer 1683/// mem-initializer , mem-initializer-list 1684void Parser::ParseConstructorInitializer(DeclPtrTy ConstructorDecl) { 1685 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1686 1687 SourceLocation ColonLoc = ConsumeToken(); 1688 1689 llvm::SmallVector<MemInitTy*, 4> MemInitializers; 1690 bool AnyErrors = false; 1691 1692 do { 1693 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1694 if (!MemInit.isInvalid()) 1695 MemInitializers.push_back(MemInit.get()); 1696 else 1697 AnyErrors = true; 1698 1699 if (Tok.is(tok::comma)) 1700 ConsumeToken(); 1701 else if (Tok.is(tok::l_brace)) 1702 break; 1703 else { 1704 // Skip over garbage, until we get to '{'. Don't eat the '{'. 1705 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 1706 SkipUntil(tok::l_brace, true, true); 1707 break; 1708 } 1709 } while (true); 1710 1711 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 1712 MemInitializers.data(), MemInitializers.size(), 1713 AnyErrors); 1714} 1715 1716/// ParseMemInitializer - Parse a C++ member initializer, which is 1717/// part of a constructor initializer that explicitly initializes one 1718/// member or base class (C++ [class.base.init]). See 1719/// ParseConstructorInitializer for an example. 1720/// 1721/// [C++] mem-initializer: 1722/// mem-initializer-id '(' expression-list[opt] ')' 1723/// 1724/// [C++] mem-initializer-id: 1725/// '::'[opt] nested-name-specifier[opt] class-name 1726/// identifier 1727Parser::MemInitResult Parser::ParseMemInitializer(DeclPtrTy ConstructorDecl) { 1728 // parse '::'[opt] nested-name-specifier[opt] 1729 CXXScopeSpec SS; 1730 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/0, false); 1731 TypeTy *TemplateTypeTy = 0; 1732 if (Tok.is(tok::annot_template_id)) { 1733 TemplateIdAnnotation *TemplateId 1734 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 1735 if (TemplateId->Kind == TNK_Type_template || 1736 TemplateId->Kind == TNK_Dependent_template_name) { 1737 AnnotateTemplateIdTokenAsType(&SS); 1738 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 1739 TemplateTypeTy = Tok.getAnnotationValue(); 1740 } 1741 } 1742 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 1743 Diag(Tok, diag::err_expected_member_or_base_name); 1744 return true; 1745 } 1746 1747 // Get the identifier. This may be a member name or a class name, 1748 // but we'll let the semantic analysis determine which it is. 1749 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 1750 SourceLocation IdLoc = ConsumeToken(); 1751 1752 // Parse the '('. 1753 if (Tok.isNot(tok::l_paren)) { 1754 Diag(Tok, diag::err_expected_lparen); 1755 return true; 1756 } 1757 SourceLocation LParenLoc = ConsumeParen(); 1758 1759 // Parse the optional expression-list. 1760 ExprVector ArgExprs(Actions); 1761 CommaLocsTy CommaLocs; 1762 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 1763 SkipUntil(tok::r_paren); 1764 return true; 1765 } 1766 1767 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1768 1769 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 1770 TemplateTypeTy, IdLoc, 1771 LParenLoc, ArgExprs.take(), 1772 ArgExprs.size(), CommaLocs.data(), 1773 RParenLoc); 1774} 1775 1776/// ParseExceptionSpecification - Parse a C++ exception-specification 1777/// (C++ [except.spec]). 1778/// 1779/// exception-specification: 1780/// 'throw' '(' type-id-list [opt] ')' 1781/// [MS] 'throw' '(' '...' ')' 1782/// 1783/// type-id-list: 1784/// type-id 1785/// type-id-list ',' type-id 1786/// 1787bool Parser::ParseExceptionSpecification(SourceLocation &EndLoc, 1788 llvm::SmallVector<TypeTy*, 2> 1789 &Exceptions, 1790 llvm::SmallVector<SourceRange, 2> 1791 &Ranges, 1792 bool &hasAnyExceptionSpec) { 1793 assert(Tok.is(tok::kw_throw) && "expected throw"); 1794 1795 SourceLocation ThrowLoc = ConsumeToken(); 1796 1797 if (!Tok.is(tok::l_paren)) { 1798 return Diag(Tok, diag::err_expected_lparen_after) << "throw"; 1799 } 1800 SourceLocation LParenLoc = ConsumeParen(); 1801 1802 // Parse throw(...), a Microsoft extension that means "this function 1803 // can throw anything". 1804 if (Tok.is(tok::ellipsis)) { 1805 hasAnyExceptionSpec = true; 1806 SourceLocation EllipsisLoc = ConsumeToken(); 1807 if (!getLang().Microsoft) 1808 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 1809 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1810 return false; 1811 } 1812 1813 // Parse the sequence of type-ids. 1814 SourceRange Range; 1815 while (Tok.isNot(tok::r_paren)) { 1816 TypeResult Res(ParseTypeName(&Range)); 1817 if (!Res.isInvalid()) { 1818 Exceptions.push_back(Res.get()); 1819 Ranges.push_back(Range); 1820 } 1821 if (Tok.is(tok::comma)) 1822 ConsumeToken(); 1823 else 1824 break; 1825 } 1826 1827 EndLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 1828 return false; 1829} 1830 1831/// \brief We have just started parsing the definition of a new class, 1832/// so push that class onto our stack of classes that is currently 1833/// being parsed. 1834void Parser::PushParsingClass(DeclPtrTy ClassDecl, bool NonNestedClass) { 1835 assert((NonNestedClass || !ClassStack.empty()) && 1836 "Nested class without outer class"); 1837 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 1838} 1839 1840/// \brief Deallocate the given parsed class and all of its nested 1841/// classes. 1842void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 1843 for (unsigned I = 0, N = Class->NestedClasses.size(); I != N; ++I) 1844 DeallocateParsedClasses(Class->NestedClasses[I]); 1845 delete Class; 1846} 1847 1848/// \brief Pop the top class of the stack of classes that are 1849/// currently being parsed. 1850/// 1851/// This routine should be called when we have finished parsing the 1852/// definition of a class, but have not yet popped the Scope 1853/// associated with the class's definition. 1854/// 1855/// \returns true if the class we've popped is a top-level class, 1856/// false otherwise. 1857void Parser::PopParsingClass() { 1858 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 1859 1860 ParsingClass *Victim = ClassStack.top(); 1861 ClassStack.pop(); 1862 if (Victim->TopLevelClass) { 1863 // Deallocate all of the nested classes of this class, 1864 // recursively: we don't need to keep any of this information. 1865 DeallocateParsedClasses(Victim); 1866 return; 1867 } 1868 assert(!ClassStack.empty() && "Missing top-level class?"); 1869 1870 if (Victim->MethodDecls.empty() && Victim->MethodDefs.empty() && 1871 Victim->NestedClasses.empty()) { 1872 // The victim is a nested class, but we will not need to perform 1873 // any processing after the definition of this class since it has 1874 // no members whose handling was delayed. Therefore, we can just 1875 // remove this nested class. 1876 delete Victim; 1877 return; 1878 } 1879 1880 // This nested class has some members that will need to be processed 1881 // after the top-level class is completely defined. Therefore, add 1882 // it to the list of nested classes within its parent. 1883 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 1884 ClassStack.top()->NestedClasses.push_back(Victim); 1885 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 1886} 1887 1888/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only 1889/// parses standard attributes. 1890/// 1891/// [C++0x] attribute-specifier: 1892/// '[' '[' attribute-list ']' ']' 1893/// 1894/// [C++0x] attribute-list: 1895/// attribute[opt] 1896/// attribute-list ',' attribute[opt] 1897/// 1898/// [C++0x] attribute: 1899/// attribute-token attribute-argument-clause[opt] 1900/// 1901/// [C++0x] attribute-token: 1902/// identifier 1903/// attribute-scoped-token 1904/// 1905/// [C++0x] attribute-scoped-token: 1906/// attribute-namespace '::' identifier 1907/// 1908/// [C++0x] attribute-namespace: 1909/// identifier 1910/// 1911/// [C++0x] attribute-argument-clause: 1912/// '(' balanced-token-seq ')' 1913/// 1914/// [C++0x] balanced-token-seq: 1915/// balanced-token 1916/// balanced-token-seq balanced-token 1917/// 1918/// [C++0x] balanced-token: 1919/// '(' balanced-token-seq ')' 1920/// '[' balanced-token-seq ']' 1921/// '{' balanced-token-seq '}' 1922/// any token but '(', ')', '[', ']', '{', or '}' 1923CXX0XAttributeList Parser::ParseCXX0XAttributes(SourceLocation *EndLoc) { 1924 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 1925 && "Not a C++0x attribute list"); 1926 1927 SourceLocation StartLoc = Tok.getLocation(), Loc; 1928 AttributeList *CurrAttr = 0; 1929 1930 ConsumeBracket(); 1931 ConsumeBracket(); 1932 1933 if (Tok.is(tok::comma)) { 1934 Diag(Tok.getLocation(), diag::err_expected_ident); 1935 ConsumeToken(); 1936 } 1937 1938 while (Tok.is(tok::identifier) || Tok.is(tok::comma)) { 1939 // attribute not present 1940 if (Tok.is(tok::comma)) { 1941 ConsumeToken(); 1942 continue; 1943 } 1944 1945 IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo(); 1946 SourceLocation ScopeLoc, AttrLoc = ConsumeToken(); 1947 1948 // scoped attribute 1949 if (Tok.is(tok::coloncolon)) { 1950 ConsumeToken(); 1951 1952 if (!Tok.is(tok::identifier)) { 1953 Diag(Tok.getLocation(), diag::err_expected_ident); 1954 SkipUntil(tok::r_square, tok::comma, true, true); 1955 continue; 1956 } 1957 1958 ScopeName = AttrName; 1959 ScopeLoc = AttrLoc; 1960 1961 AttrName = Tok.getIdentifierInfo(); 1962 AttrLoc = ConsumeToken(); 1963 } 1964 1965 bool AttrParsed = false; 1966 // No scoped names are supported; ideally we could put all non-standard 1967 // attributes into namespaces. 1968 if (!ScopeName) { 1969 switch(AttributeList::getKind(AttrName)) 1970 { 1971 // No arguments 1972 case AttributeList::AT_base_check: 1973 case AttributeList::AT_carries_dependency: 1974 case AttributeList::AT_final: 1975 case AttributeList::AT_hiding: 1976 case AttributeList::AT_noreturn: 1977 case AttributeList::AT_override: { 1978 if (Tok.is(tok::l_paren)) { 1979 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments) 1980 << AttrName->getName(); 1981 break; 1982 } 1983 1984 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 0, 1985 SourceLocation(), 0, 0, CurrAttr, false, 1986 true); 1987 AttrParsed = true; 1988 break; 1989 } 1990 1991 // One argument; must be a type-id or assignment-expression 1992 case AttributeList::AT_aligned: { 1993 if (Tok.isNot(tok::l_paren)) { 1994 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments) 1995 << AttrName->getName(); 1996 break; 1997 } 1998 SourceLocation ParamLoc = ConsumeParen(); 1999 2000 OwningExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc); 2001 2002 MatchRHSPunctuation(tok::r_paren, ParamLoc); 2003 2004 ExprVector ArgExprs(Actions); 2005 ArgExprs.push_back(ArgExpr.release()); 2006 CurrAttr = new AttributeList(AttrName, AttrLoc, 0, AttrLoc, 2007 0, ParamLoc, ArgExprs.take(), 1, CurrAttr, 2008 false, true); 2009 2010 AttrParsed = true; 2011 break; 2012 } 2013 2014 // Silence warnings 2015 default: break; 2016 } 2017 } 2018 2019 // Skip the entire parameter clause, if any 2020 if (!AttrParsed && Tok.is(tok::l_paren)) { 2021 ConsumeParen(); 2022 // SkipUntil maintains the balancedness of tokens. 2023 SkipUntil(tok::r_paren, false); 2024 } 2025 } 2026 2027 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2028 SkipUntil(tok::r_square, false); 2029 Loc = Tok.getLocation(); 2030 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2031 SkipUntil(tok::r_square, false); 2032 2033 CXX0XAttributeList Attr (CurrAttr, SourceRange(StartLoc, Loc), true); 2034 return Attr; 2035} 2036 2037/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]] 2038/// attribute. 2039/// 2040/// FIXME: Simply returns an alignof() expression if the argument is a 2041/// type. Ideally, the type should be propagated directly into Sema. 2042/// 2043/// [C++0x] 'align' '(' type-id ')' 2044/// [C++0x] 'align' '(' assignment-expression ')' 2045Parser::OwningExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) { 2046 if (isTypeIdInParens()) { 2047 EnterExpressionEvaluationContext Unevaluated(Actions, 2048 Action::Unevaluated); 2049 SourceLocation TypeLoc = Tok.getLocation(); 2050 TypeTy *Ty = ParseTypeName().get(); 2051 SourceRange TypeRange(Start, Tok.getLocation()); 2052 return Actions.ActOnSizeOfAlignOfExpr(TypeLoc, false, true, Ty, 2053 TypeRange); 2054 } else 2055 return ParseConstantExpression(); 2056} 2057