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