ParseDeclCXX.cpp revision bb85f8edca8103aa10e4b2f4a6fcc3a251b0ea03
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 SourceLocation DefaultLoc; 1652 1653 while (1) { 1654 // member-declarator: 1655 // declarator pure-specifier[opt] 1656 // declarator constant-initializer[opt] 1657 // identifier[opt] ':' constant-expression 1658 if (Tok.is(tok::colon)) { 1659 ConsumeToken(); 1660 BitfieldSize = ParseConstantExpression(); 1661 if (BitfieldSize.isInvalid()) 1662 SkipUntil(tok::comma, true, true); 1663 } 1664 1665 ParseOptionalCXX0XVirtSpecifierSeq(VS); 1666 1667 // pure-specifier: 1668 // '= 0' 1669 // 1670 // constant-initializer: 1671 // '=' constant-expression 1672 // 1673 // defaulted/deleted function-definition: 1674 // '=' 'default' [TODO] 1675 // '=' 'delete' 1676 if (Tok.is(tok::equal)) { 1677 ConsumeToken(); 1678 if (Tok.is(tok::kw_delete)) { 1679 if (!getLang().CPlusPlus0x) 1680 Diag(Tok, diag::warn_deleted_function_accepted_as_extension); 1681 ConsumeToken(); 1682 Deleted = true; 1683 } else if (Tok.is(tok::kw_default)) { 1684 if (!getLang().CPlusPlus0x) 1685 Diag(Tok, diag::warn_defaulted_function_accepted_as_extension); 1686 DefaultLoc = ConsumeToken(); 1687 } else { 1688 Init = ParseInitializer(); 1689 if (Init.isInvalid()) 1690 SkipUntil(tok::comma, true, true); 1691 } 1692 } 1693 1694 // If a simple-asm-expr is present, parse it. 1695 if (Tok.is(tok::kw_asm)) { 1696 SourceLocation Loc; 1697 ExprResult AsmLabel(ParseSimpleAsm(&Loc)); 1698 if (AsmLabel.isInvalid()) 1699 SkipUntil(tok::comma, true, true); 1700 1701 DeclaratorInfo.setAsmLabel(AsmLabel.release()); 1702 DeclaratorInfo.SetRangeEnd(Loc); 1703 } 1704 1705 // If attributes exist after the declarator, parse them. 1706 MaybeParseGNUAttributes(DeclaratorInfo); 1707 1708 // NOTE: If Sema is the Action module and declarator is an instance field, 1709 // this call will *not* return the created decl; It will return null. 1710 // See Sema::ActOnCXXMemberDeclarator for details. 1711 1712 Decl *ThisDecl = 0; 1713 if (DS.isFriendSpecified()) { 1714 if (DefaultLoc.isValid()) 1715 Diag(DefaultLoc, diag::err_default_special_members); 1716 1717 // TODO: handle initializers, bitfields, 'delete' 1718 ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, 1719 /*IsDefinition*/ false, 1720 move(TemplateParams)); 1721 } else { 1722 ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, 1723 DeclaratorInfo, 1724 move(TemplateParams), 1725 BitfieldSize.release(), 1726 VS, Init.release(), 1727 /*IsDefinition*/Deleted, 1728 Deleted, DefaultLoc); 1729 } 1730 if (ThisDecl) 1731 DeclsInGroup.push_back(ThisDecl); 1732 1733 if (DeclaratorInfo.isFunctionDeclarator() && 1734 DeclaratorInfo.getDeclSpec().getStorageClassSpec() 1735 != DeclSpec::SCS_typedef) { 1736 HandleMemberFunctionDefaultArgs(DeclaratorInfo, ThisDecl); 1737 } 1738 1739 DeclaratorInfo.complete(ThisDecl); 1740 1741 // If we don't have a comma, it is either the end of the list (a ';') 1742 // or an error, bail out. 1743 if (Tok.isNot(tok::comma)) 1744 break; 1745 1746 // Consume the comma. 1747 ConsumeToken(); 1748 1749 // Parse the next declarator. 1750 DeclaratorInfo.clear(); 1751 VS.clear(); 1752 BitfieldSize = 0; 1753 Init = 0; 1754 Deleted = false; 1755 DefaultLoc = SourceLocation(); 1756 1757 // Attributes are only allowed on the second declarator. 1758 MaybeParseGNUAttributes(DeclaratorInfo); 1759 1760 if (Tok.isNot(tok::colon)) 1761 ParseDeclarator(DeclaratorInfo); 1762 } 1763 1764 if (ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { 1765 // Skip to end of block or statement. 1766 SkipUntil(tok::r_brace, true, true); 1767 // If we stopped at a ';', eat it. 1768 if (Tok.is(tok::semi)) ConsumeToken(); 1769 return; 1770 } 1771 1772 Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup.data(), 1773 DeclsInGroup.size()); 1774} 1775 1776/// ParseCXXMemberSpecification - Parse the class definition. 1777/// 1778/// member-specification: 1779/// member-declaration member-specification[opt] 1780/// access-specifier ':' member-specification[opt] 1781/// 1782void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 1783 unsigned TagType, Decl *TagDecl) { 1784 assert((TagType == DeclSpec::TST_struct || 1785 TagType == DeclSpec::TST_union || 1786 TagType == DeclSpec::TST_class) && "Invalid TagType!"); 1787 1788 PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, 1789 "parsing struct/union/class body"); 1790 1791 // Determine whether this is a non-nested class. Note that local 1792 // classes are *not* considered to be nested classes. 1793 bool NonNestedClass = true; 1794 if (!ClassStack.empty()) { 1795 for (const Scope *S = getCurScope(); S; S = S->getParent()) { 1796 if (S->isClassScope()) { 1797 // We're inside a class scope, so this is a nested class. 1798 NonNestedClass = false; 1799 break; 1800 } 1801 1802 if ((S->getFlags() & Scope::FnScope)) { 1803 // If we're in a function or function template declared in the 1804 // body of a class, then this is a local class rather than a 1805 // nested class. 1806 const Scope *Parent = S->getParent(); 1807 if (Parent->isTemplateParamScope()) 1808 Parent = Parent->getParent(); 1809 if (Parent->isClassScope()) 1810 break; 1811 } 1812 } 1813 } 1814 1815 // Enter a scope for the class. 1816 ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); 1817 1818 // Note that we are parsing a new (potentially-nested) class definition. 1819 ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass); 1820 1821 if (TagDecl) 1822 Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); 1823 1824 SourceLocation FinalLoc; 1825 1826 // Parse the optional 'final' keyword. 1827 if (getLang().CPlusPlus && Tok.is(tok::identifier)) { 1828 IdentifierInfo *II = Tok.getIdentifierInfo(); 1829 1830 // Initialize the contextual keywords. 1831 if (!Ident_final) { 1832 Ident_final = &PP.getIdentifierTable().get("final"); 1833 Ident_override = &PP.getIdentifierTable().get("override"); 1834 } 1835 1836 if (II == Ident_final) 1837 FinalLoc = ConsumeToken(); 1838 1839 if (!getLang().CPlusPlus0x) 1840 Diag(FinalLoc, diag::ext_override_control_keyword) << "final"; 1841 } 1842 1843 if (Tok.is(tok::colon)) { 1844 ParseBaseClause(TagDecl); 1845 1846 if (!Tok.is(tok::l_brace)) { 1847 Diag(Tok, diag::err_expected_lbrace_after_base_specifiers); 1848 1849 if (TagDecl) 1850 Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); 1851 return; 1852 } 1853 } 1854 1855 assert(Tok.is(tok::l_brace)); 1856 1857 SourceLocation LBraceLoc = ConsumeBrace(); 1858 1859 if (TagDecl) 1860 Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, 1861 LBraceLoc); 1862 1863 // C++ 11p3: Members of a class defined with the keyword class are private 1864 // by default. Members of a class defined with the keywords struct or union 1865 // are public by default. 1866 AccessSpecifier CurAS; 1867 if (TagType == DeclSpec::TST_class) 1868 CurAS = AS_private; 1869 else 1870 CurAS = AS_public; 1871 1872 SourceLocation RBraceLoc; 1873 if (TagDecl) { 1874 // While we still have something to read, read the member-declarations. 1875 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 1876 // Each iteration of this loop reads one member-declaration. 1877 1878 // Check for extraneous top-level semicolon. 1879 if (Tok.is(tok::semi)) { 1880 Diag(Tok, diag::ext_extra_struct_semi) 1881 << DeclSpec::getSpecifierName((DeclSpec::TST)TagType) 1882 << FixItHint::CreateRemoval(Tok.getLocation()); 1883 ConsumeToken(); 1884 continue; 1885 } 1886 1887 AccessSpecifier AS = getAccessSpecifierIfPresent(); 1888 if (AS != AS_none) { 1889 // Current token is a C++ access specifier. 1890 CurAS = AS; 1891 SourceLocation ASLoc = Tok.getLocation(); 1892 ConsumeToken(); 1893 if (Tok.is(tok::colon)) 1894 Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); 1895 else 1896 Diag(Tok, diag::err_expected_colon); 1897 ConsumeToken(); 1898 continue; 1899 } 1900 1901 // FIXME: Make sure we don't have a template here. 1902 1903 // Parse all the comma separated declarators. 1904 ParseCXXClassMemberDeclaration(CurAS); 1905 } 1906 1907 RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 1908 } else { 1909 SkipUntil(tok::r_brace, false, false); 1910 } 1911 1912 // If attributes exist after class contents, parse them. 1913 ParsedAttributes attrs(AttrFactory); 1914 MaybeParseGNUAttributes(attrs); 1915 1916 if (TagDecl) 1917 Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, 1918 LBraceLoc, RBraceLoc, 1919 attrs.getList()); 1920 1921 // C++ 9.2p2: Within the class member-specification, the class is regarded as 1922 // complete within function bodies, default arguments, 1923 // exception-specifications, and constructor ctor-initializers (including 1924 // such things in nested classes). 1925 // 1926 // FIXME: Only function bodies and constructor ctor-initializers are 1927 // parsed correctly, fix the rest. 1928 if (TagDecl && NonNestedClass) { 1929 // We are not inside a nested class. This class and its nested classes 1930 // are complete and we can parse the delayed portions of method 1931 // declarations and the lexed inline method definitions. 1932 SourceLocation SavedPrevTokLocation = PrevTokLocation; 1933 ParseLexedMethodDeclarations(getCurrentClass()); 1934 ParseLexedMethodDefs(getCurrentClass()); 1935 PrevTokLocation = SavedPrevTokLocation; 1936 } 1937 1938 if (TagDecl) 1939 Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, RBraceLoc); 1940 1941 // Leave the class scope. 1942 ParsingDef.Pop(); 1943 ClassScope.Exit(); 1944} 1945 1946/// ParseConstructorInitializer - Parse a C++ constructor initializer, 1947/// which explicitly initializes the members or base classes of a 1948/// class (C++ [class.base.init]). For example, the three initializers 1949/// after the ':' in the Derived constructor below: 1950/// 1951/// @code 1952/// class Base { }; 1953/// class Derived : Base { 1954/// int x; 1955/// float f; 1956/// public: 1957/// Derived(float f) : Base(), x(17), f(f) { } 1958/// }; 1959/// @endcode 1960/// 1961/// [C++] ctor-initializer: 1962/// ':' mem-initializer-list 1963/// 1964/// [C++] mem-initializer-list: 1965/// mem-initializer ...[opt] 1966/// mem-initializer ...[opt] , mem-initializer-list 1967void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { 1968 assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); 1969 1970 // Poison the SEH identifiers so they are flagged as illegal in constructor initializers 1971 PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); 1972 SourceLocation ColonLoc = ConsumeToken(); 1973 1974 llvm::SmallVector<CXXCtorInitializer*, 4> MemInitializers; 1975 bool AnyErrors = false; 1976 1977 do { 1978 if (Tok.is(tok::code_completion)) { 1979 Actions.CodeCompleteConstructorInitializer(ConstructorDecl, 1980 MemInitializers.data(), 1981 MemInitializers.size()); 1982 ConsumeCodeCompletionToken(); 1983 } else { 1984 MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); 1985 if (!MemInit.isInvalid()) 1986 MemInitializers.push_back(MemInit.get()); 1987 else 1988 AnyErrors = true; 1989 } 1990 1991 if (Tok.is(tok::comma)) 1992 ConsumeToken(); 1993 else if (Tok.is(tok::l_brace)) 1994 break; 1995 // If the next token looks like a base or member initializer, assume that 1996 // we're just missing a comma. 1997 else if (Tok.is(tok::identifier) || Tok.is(tok::coloncolon)) { 1998 SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); 1999 Diag(Loc, diag::err_ctor_init_missing_comma) 2000 << FixItHint::CreateInsertion(Loc, ", "); 2001 } else { 2002 // Skip over garbage, until we get to '{'. Don't eat the '{'. 2003 Diag(Tok.getLocation(), diag::err_expected_lbrace_or_comma); 2004 SkipUntil(tok::l_brace, true, true); 2005 break; 2006 } 2007 } while (true); 2008 2009 Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, 2010 MemInitializers.data(), MemInitializers.size(), 2011 AnyErrors); 2012} 2013 2014/// ParseMemInitializer - Parse a C++ member initializer, which is 2015/// part of a constructor initializer that explicitly initializes one 2016/// member or base class (C++ [class.base.init]). See 2017/// ParseConstructorInitializer for an example. 2018/// 2019/// [C++] mem-initializer: 2020/// mem-initializer-id '(' expression-list[opt] ')' 2021/// 2022/// [C++] mem-initializer-id: 2023/// '::'[opt] nested-name-specifier[opt] class-name 2024/// identifier 2025Parser::MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { 2026 // parse '::'[opt] nested-name-specifier[opt] 2027 CXXScopeSpec SS; 2028 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false); 2029 ParsedType TemplateTypeTy; 2030 if (Tok.is(tok::annot_template_id)) { 2031 TemplateIdAnnotation *TemplateId 2032 = static_cast<TemplateIdAnnotation *>(Tok.getAnnotationValue()); 2033 if (TemplateId->Kind == TNK_Type_template || 2034 TemplateId->Kind == TNK_Dependent_template_name) { 2035 AnnotateTemplateIdTokenAsType(); 2036 assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); 2037 TemplateTypeTy = getTypeAnnotation(Tok); 2038 } 2039 } 2040 if (!TemplateTypeTy && Tok.isNot(tok::identifier)) { 2041 Diag(Tok, diag::err_expected_member_or_base_name); 2042 return true; 2043 } 2044 2045 // Get the identifier. This may be a member name or a class name, 2046 // but we'll let the semantic analysis determine which it is. 2047 IdentifierInfo *II = Tok.is(tok::identifier) ? Tok.getIdentifierInfo() : 0; 2048 SourceLocation IdLoc = ConsumeToken(); 2049 2050 // Parse the '('. 2051 if (Tok.isNot(tok::l_paren)) { 2052 Diag(Tok, diag::err_expected_lparen); 2053 return true; 2054 } 2055 SourceLocation LParenLoc = ConsumeParen(); 2056 2057 // Parse the optional expression-list. 2058 ExprVector ArgExprs(Actions); 2059 CommaLocsTy CommaLocs; 2060 if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { 2061 SkipUntil(tok::r_paren); 2062 return true; 2063 } 2064 2065 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2066 2067 SourceLocation EllipsisLoc; 2068 if (Tok.is(tok::ellipsis)) 2069 EllipsisLoc = ConsumeToken(); 2070 2071 return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, 2072 TemplateTypeTy, IdLoc, 2073 LParenLoc, ArgExprs.take(), 2074 ArgExprs.size(), RParenLoc, 2075 EllipsisLoc); 2076} 2077 2078/// \brief Parse a C++ exception-specification if present (C++0x [except.spec]). 2079/// 2080/// exception-specification: 2081/// dynamic-exception-specification 2082/// noexcept-specification 2083/// 2084/// noexcept-specification: 2085/// 'noexcept' 2086/// 'noexcept' '(' constant-expression ')' 2087ExceptionSpecificationType 2088Parser::MaybeParseExceptionSpecification(SourceRange &SpecificationRange, 2089 llvm::SmallVectorImpl<ParsedType> &DynamicExceptions, 2090 llvm::SmallVectorImpl<SourceRange> &DynamicExceptionRanges, 2091 ExprResult &NoexceptExpr) { 2092 ExceptionSpecificationType Result = EST_None; 2093 2094 // See if there's a dynamic specification. 2095 if (Tok.is(tok::kw_throw)) { 2096 Result = ParseDynamicExceptionSpecification(SpecificationRange, 2097 DynamicExceptions, 2098 DynamicExceptionRanges); 2099 assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && 2100 "Produced different number of exception types and ranges."); 2101 } 2102 2103 // If there's no noexcept specification, we're done. 2104 if (Tok.isNot(tok::kw_noexcept)) 2105 return Result; 2106 2107 // If we already had a dynamic specification, parse the noexcept for, 2108 // recovery, but emit a diagnostic and don't store the results. 2109 SourceRange NoexceptRange; 2110 ExceptionSpecificationType NoexceptType = EST_None; 2111 2112 SourceLocation KeywordLoc = ConsumeToken(); 2113 if (Tok.is(tok::l_paren)) { 2114 // There is an argument. 2115 SourceLocation LParenLoc = ConsumeParen(); 2116 NoexceptType = EST_ComputedNoexcept; 2117 NoexceptExpr = ParseConstantExpression(); 2118 // The argument must be contextually convertible to bool. We use 2119 // ActOnBooleanCondition for this purpose. 2120 if (!NoexceptExpr.isInvalid()) 2121 NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc, 2122 NoexceptExpr.get()); 2123 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2124 NoexceptRange = SourceRange(KeywordLoc, RParenLoc); 2125 } else { 2126 // There is no argument. 2127 NoexceptType = EST_BasicNoexcept; 2128 NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); 2129 } 2130 2131 if (Result == EST_None) { 2132 SpecificationRange = NoexceptRange; 2133 Result = NoexceptType; 2134 2135 // If there's a dynamic specification after a noexcept specification, 2136 // parse that and ignore the results. 2137 if (Tok.is(tok::kw_throw)) { 2138 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2139 ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, 2140 DynamicExceptionRanges); 2141 } 2142 } else { 2143 Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); 2144 } 2145 2146 return Result; 2147} 2148 2149/// ParseDynamicExceptionSpecification - Parse a C++ 2150/// dynamic-exception-specification (C++ [except.spec]). 2151/// 2152/// dynamic-exception-specification: 2153/// 'throw' '(' type-id-list [opt] ')' 2154/// [MS] 'throw' '(' '...' ')' 2155/// 2156/// type-id-list: 2157/// type-id ... [opt] 2158/// type-id-list ',' type-id ... [opt] 2159/// 2160ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( 2161 SourceRange &SpecificationRange, 2162 llvm::SmallVectorImpl<ParsedType> &Exceptions, 2163 llvm::SmallVectorImpl<SourceRange> &Ranges) { 2164 assert(Tok.is(tok::kw_throw) && "expected throw"); 2165 2166 SpecificationRange.setBegin(ConsumeToken()); 2167 2168 if (!Tok.is(tok::l_paren)) { 2169 Diag(Tok, diag::err_expected_lparen_after) << "throw"; 2170 SpecificationRange.setEnd(SpecificationRange.getBegin()); 2171 return EST_DynamicNone; 2172 } 2173 SourceLocation LParenLoc = ConsumeParen(); 2174 2175 // Parse throw(...), a Microsoft extension that means "this function 2176 // can throw anything". 2177 if (Tok.is(tok::ellipsis)) { 2178 SourceLocation EllipsisLoc = ConsumeToken(); 2179 if (!getLang().Microsoft) 2180 Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); 2181 SourceLocation RParenLoc = MatchRHSPunctuation(tok::r_paren, LParenLoc); 2182 SpecificationRange.setEnd(RParenLoc); 2183 return EST_MSAny; 2184 } 2185 2186 // Parse the sequence of type-ids. 2187 SourceRange Range; 2188 while (Tok.isNot(tok::r_paren)) { 2189 TypeResult Res(ParseTypeName(&Range)); 2190 2191 if (Tok.is(tok::ellipsis)) { 2192 // C++0x [temp.variadic]p5: 2193 // - In a dynamic-exception-specification (15.4); the pattern is a 2194 // type-id. 2195 SourceLocation Ellipsis = ConsumeToken(); 2196 Range.setEnd(Ellipsis); 2197 if (!Res.isInvalid()) 2198 Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); 2199 } 2200 2201 if (!Res.isInvalid()) { 2202 Exceptions.push_back(Res.get()); 2203 Ranges.push_back(Range); 2204 } 2205 2206 if (Tok.is(tok::comma)) 2207 ConsumeToken(); 2208 else 2209 break; 2210 } 2211 2212 SpecificationRange.setEnd(MatchRHSPunctuation(tok::r_paren, LParenLoc)); 2213 return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; 2214} 2215 2216/// ParseTrailingReturnType - Parse a trailing return type on a new-style 2217/// function declaration. 2218TypeResult Parser::ParseTrailingReturnType() { 2219 assert(Tok.is(tok::arrow) && "expected arrow"); 2220 2221 ConsumeToken(); 2222 2223 // FIXME: Need to suppress declarations when parsing this typename. 2224 // Otherwise in this function definition: 2225 // 2226 // auto f() -> struct X {} 2227 // 2228 // struct X is parsed as class definition because of the trailing 2229 // brace. 2230 2231 SourceRange Range; 2232 return ParseTypeName(&Range); 2233} 2234 2235/// \brief We have just started parsing the definition of a new class, 2236/// so push that class onto our stack of classes that is currently 2237/// being parsed. 2238Sema::ParsingClassState 2239Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass) { 2240 assert((NonNestedClass || !ClassStack.empty()) && 2241 "Nested class without outer class"); 2242 ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass)); 2243 return Actions.PushParsingClass(); 2244} 2245 2246/// \brief Deallocate the given parsed class and all of its nested 2247/// classes. 2248void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { 2249 for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) 2250 delete Class->LateParsedDeclarations[I]; 2251 delete Class; 2252} 2253 2254/// \brief Pop the top class of the stack of classes that are 2255/// currently being parsed. 2256/// 2257/// This routine should be called when we have finished parsing the 2258/// definition of a class, but have not yet popped the Scope 2259/// associated with the class's definition. 2260/// 2261/// \returns true if the class we've popped is a top-level class, 2262/// false otherwise. 2263void Parser::PopParsingClass(Sema::ParsingClassState state) { 2264 assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); 2265 2266 Actions.PopParsingClass(state); 2267 2268 ParsingClass *Victim = ClassStack.top(); 2269 ClassStack.pop(); 2270 if (Victim->TopLevelClass) { 2271 // Deallocate all of the nested classes of this class, 2272 // recursively: we don't need to keep any of this information. 2273 DeallocateParsedClasses(Victim); 2274 return; 2275 } 2276 assert(!ClassStack.empty() && "Missing top-level class?"); 2277 2278 if (Victim->LateParsedDeclarations.empty()) { 2279 // The victim is a nested class, but we will not need to perform 2280 // any processing after the definition of this class since it has 2281 // no members whose handling was delayed. Therefore, we can just 2282 // remove this nested class. 2283 DeallocateParsedClasses(Victim); 2284 return; 2285 } 2286 2287 // This nested class has some members that will need to be processed 2288 // after the top-level class is completely defined. Therefore, add 2289 // it to the list of nested classes within its parent. 2290 assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); 2291 ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim)); 2292 Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); 2293} 2294 2295/// ParseCXX0XAttributes - Parse a C++0x attribute-specifier. Currently only 2296/// parses standard attributes. 2297/// 2298/// [C++0x] attribute-specifier: 2299/// '[' '[' attribute-list ']' ']' 2300/// 2301/// [C++0x] attribute-list: 2302/// attribute[opt] 2303/// attribute-list ',' attribute[opt] 2304/// 2305/// [C++0x] attribute: 2306/// attribute-token attribute-argument-clause[opt] 2307/// 2308/// [C++0x] attribute-token: 2309/// identifier 2310/// attribute-scoped-token 2311/// 2312/// [C++0x] attribute-scoped-token: 2313/// attribute-namespace '::' identifier 2314/// 2315/// [C++0x] attribute-namespace: 2316/// identifier 2317/// 2318/// [C++0x] attribute-argument-clause: 2319/// '(' balanced-token-seq ')' 2320/// 2321/// [C++0x] balanced-token-seq: 2322/// balanced-token 2323/// balanced-token-seq balanced-token 2324/// 2325/// [C++0x] balanced-token: 2326/// '(' balanced-token-seq ')' 2327/// '[' balanced-token-seq ']' 2328/// '{' balanced-token-seq '}' 2329/// any token but '(', ')', '[', ']', '{', or '}' 2330void Parser::ParseCXX0XAttributes(ParsedAttributesWithRange &attrs, 2331 SourceLocation *endLoc) { 2332 assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) 2333 && "Not a C++0x attribute list"); 2334 2335 SourceLocation StartLoc = Tok.getLocation(), Loc; 2336 2337 ConsumeBracket(); 2338 ConsumeBracket(); 2339 2340 if (Tok.is(tok::comma)) { 2341 Diag(Tok.getLocation(), diag::err_expected_ident); 2342 ConsumeToken(); 2343 } 2344 2345 while (Tok.is(tok::identifier) || Tok.is(tok::comma)) { 2346 // attribute not present 2347 if (Tok.is(tok::comma)) { 2348 ConsumeToken(); 2349 continue; 2350 } 2351 2352 IdentifierInfo *ScopeName = 0, *AttrName = Tok.getIdentifierInfo(); 2353 SourceLocation ScopeLoc, AttrLoc = ConsumeToken(); 2354 2355 // scoped attribute 2356 if (Tok.is(tok::coloncolon)) { 2357 ConsumeToken(); 2358 2359 if (!Tok.is(tok::identifier)) { 2360 Diag(Tok.getLocation(), diag::err_expected_ident); 2361 SkipUntil(tok::r_square, tok::comma, true, true); 2362 continue; 2363 } 2364 2365 ScopeName = AttrName; 2366 ScopeLoc = AttrLoc; 2367 2368 AttrName = Tok.getIdentifierInfo(); 2369 AttrLoc = ConsumeToken(); 2370 } 2371 2372 bool AttrParsed = false; 2373 // No scoped names are supported; ideally we could put all non-standard 2374 // attributes into namespaces. 2375 if (!ScopeName) { 2376 switch(AttributeList::getKind(AttrName)) 2377 { 2378 // No arguments 2379 case AttributeList::AT_carries_dependency: 2380 case AttributeList::AT_noreturn: { 2381 if (Tok.is(tok::l_paren)) { 2382 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_forbids_arguments) 2383 << AttrName->getName(); 2384 break; 2385 } 2386 2387 attrs.addNew(AttrName, AttrLoc, 0, AttrLoc, 0, 2388 SourceLocation(), 0, 0, false, true); 2389 AttrParsed = true; 2390 break; 2391 } 2392 2393 // One argument; must be a type-id or assignment-expression 2394 case AttributeList::AT_aligned: { 2395 if (Tok.isNot(tok::l_paren)) { 2396 Diag(Tok.getLocation(), diag::err_cxx0x_attribute_requires_arguments) 2397 << AttrName->getName(); 2398 break; 2399 } 2400 SourceLocation ParamLoc = ConsumeParen(); 2401 2402 ExprResult ArgExpr = ParseCXX0XAlignArgument(ParamLoc); 2403 2404 MatchRHSPunctuation(tok::r_paren, ParamLoc); 2405 2406 ExprVector ArgExprs(Actions); 2407 ArgExprs.push_back(ArgExpr.release()); 2408 attrs.addNew(AttrName, AttrLoc, 0, AttrLoc, 2409 0, ParamLoc, ArgExprs.take(), 1, 2410 false, true); 2411 2412 AttrParsed = true; 2413 break; 2414 } 2415 2416 // Silence warnings 2417 default: break; 2418 } 2419 } 2420 2421 // Skip the entire parameter clause, if any 2422 if (!AttrParsed && Tok.is(tok::l_paren)) { 2423 ConsumeParen(); 2424 // SkipUntil maintains the balancedness of tokens. 2425 SkipUntil(tok::r_paren, false); 2426 } 2427 } 2428 2429 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2430 SkipUntil(tok::r_square, false); 2431 Loc = Tok.getLocation(); 2432 if (ExpectAndConsume(tok::r_square, diag::err_expected_rsquare)) 2433 SkipUntil(tok::r_square, false); 2434 2435 attrs.Range = SourceRange(StartLoc, Loc); 2436} 2437 2438/// ParseCXX0XAlignArgument - Parse the argument to C++0x's [[align]] 2439/// attribute. 2440/// 2441/// FIXME: Simply returns an alignof() expression if the argument is a 2442/// type. Ideally, the type should be propagated directly into Sema. 2443/// 2444/// [C++0x] 'align' '(' type-id ')' 2445/// [C++0x] 'align' '(' assignment-expression ')' 2446ExprResult Parser::ParseCXX0XAlignArgument(SourceLocation Start) { 2447 if (isTypeIdInParens()) { 2448 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); 2449 SourceLocation TypeLoc = Tok.getLocation(); 2450 ParsedType Ty = ParseTypeName().get(); 2451 SourceRange TypeRange(Start, Tok.getLocation()); 2452 return Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, 2453 Ty.getAsOpaquePtr(), TypeRange); 2454 } else 2455 return ParseConstantExpression(); 2456} 2457 2458/// ParseMicrosoftAttributes - Parse a Microsoft attribute [Attr] 2459/// 2460/// [MS] ms-attribute: 2461/// '[' token-seq ']' 2462/// 2463/// [MS] ms-attribute-seq: 2464/// ms-attribute[opt] 2465/// ms-attribute ms-attribute-seq 2466void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs, 2467 SourceLocation *endLoc) { 2468 assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); 2469 2470 while (Tok.is(tok::l_square)) { 2471 ConsumeBracket(); 2472 SkipUntil(tok::r_square, true, true); 2473 if (endLoc) *endLoc = Tok.getLocation(); 2474 ExpectAndConsume(tok::r_square, diag::err_expected_rsquare); 2475 } 2476} 2477