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