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