ParseDeclCXX.cpp revision 4cc18a4d5222e04bd568b1e3e4d86127dbbcdf3f
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/Parse/Parser.h" 15#include "clang/Basic/Diagnostic.h" 16#include "clang/Parse/DeclSpec.h" 17#include "clang/Parse/Scope.h" 18using namespace clang; 19 20/// ParseNamespace - We know that the current token is a namespace keyword. This 21/// may either be a top level namespace or a block-level namespace alias. 22/// 23/// namespace-definition: [C++ 7.3: basic.namespace] 24/// named-namespace-definition 25/// unnamed-namespace-definition 26/// 27/// unnamed-namespace-definition: 28/// 'namespace' attributes[opt] '{' namespace-body '}' 29/// 30/// named-namespace-definition: 31/// original-namespace-definition 32/// extension-namespace-definition 33/// 34/// original-namespace-definition: 35/// 'namespace' identifier attributes[opt] '{' namespace-body '}' 36/// 37/// extension-namespace-definition: 38/// 'namespace' original-namespace-name '{' namespace-body '}' 39/// 40/// namespace-alias-definition: [C++ 7.3.2: namespace.alias] 41/// 'namespace' identifier '=' qualified-namespace-specifier ';' 42/// 43Parser::DeclTy *Parser::ParseNamespace(unsigned Context) { 44 assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); 45 SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. 46 47 SourceLocation IdentLoc; 48 IdentifierInfo *Ident = 0; 49 50 if (Tok.is(tok::identifier)) { 51 Ident = Tok.getIdentifierInfo(); 52 IdentLoc = ConsumeToken(); // eat the identifier. 53 } 54 55 // Read label attributes, if present. 56 DeclTy *AttrList = 0; 57 if (Tok.is(tok::kw___attribute)) 58 // FIXME: save these somewhere. 59 AttrList = ParseAttributes(); 60 61 if (Tok.is(tok::equal)) { 62 // FIXME: Verify no attributes were present. 63 // FIXME: parse this. 64 } else if (Tok.is(tok::l_brace)) { 65 66 SourceLocation LBrace = ConsumeBrace(); 67 68 // Enter a scope for the namespace. 69 EnterScope(Scope::DeclScope); 70 71 DeclTy *NamespcDecl = 72 Actions.ActOnStartNamespaceDef(CurScope, IdentLoc, Ident, LBrace); 73 74 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) 75 ParseExternalDeclaration(); 76 77 // Leave the namespace scope. 78 ExitScope(); 79 80 SourceLocation RBrace = MatchRHSPunctuation(tok::r_brace, LBrace); 81 Actions.ActOnFinishNamespaceDef(NamespcDecl, RBrace); 82 83 return NamespcDecl; 84 85 } else { 86 unsigned D = Ident ? diag::err_expected_lbrace : 87 diag::err_expected_ident_lbrace; 88 Diag(Tok.getLocation(), D); 89 } 90 91 return 0; 92} 93 94/// ParseLinkage - We know that the current token is a string_literal 95/// and just before that, that extern was seen. 96/// 97/// linkage-specification: [C++ 7.5p2: dcl.link] 98/// 'extern' string-literal '{' declaration-seq[opt] '}' 99/// 'extern' string-literal declaration 100/// 101Parser::DeclTy *Parser::ParseLinkage(unsigned Context) { 102 assert(Tok.is(tok::string_literal) && "Not a stringliteral!"); 103 llvm::SmallVector<char, 8> LangBuffer; 104 // LangBuffer is guaranteed to be big enough. 105 LangBuffer.resize(Tok.getLength()); 106 const char *LangBufPtr = &LangBuffer[0]; 107 unsigned StrSize = PP.getSpelling(Tok, LangBufPtr); 108 109 SourceLocation Loc = ConsumeStringToken(); 110 DeclTy *D = 0; 111 SourceLocation LBrace, RBrace; 112 113 if (Tok.isNot(tok::l_brace)) { 114 D = ParseDeclaration(Context); 115 } else { 116 LBrace = ConsumeBrace(); 117 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 118 // FIXME capture the decls. 119 D = ParseExternalDeclaration(); 120 } 121 122 RBrace = MatchRHSPunctuation(tok::r_brace, LBrace); 123 } 124 125 if (!D) 126 return 0; 127 128 return Actions.ActOnLinkageSpec(Loc, LBrace, RBrace, LangBufPtr, StrSize, D); 129} 130 131/// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or 132/// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which 133/// until we reach the start of a definition or see a token that 134/// cannot start a definition. 135/// 136/// class-specifier: [C++ class] 137/// class-head '{' member-specification[opt] '}' 138/// class-head '{' member-specification[opt] '}' attributes[opt] 139/// class-head: 140/// class-key identifier[opt] base-clause[opt] 141/// class-key nested-name-specifier identifier base-clause[opt] 142/// class-key nested-name-specifier[opt] simple-template-id 143/// base-clause[opt] 144/// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] 145/// [GNU] class-key attributes[opt] nested-name-specifier 146/// identifier base-clause[opt] 147/// [GNU] class-key attributes[opt] nested-name-specifier[opt] 148/// simple-template-id base-clause[opt] 149/// class-key: 150/// 'class' 151/// 'struct' 152/// 'union' 153/// 154/// elaborated-type-specifier: [C++ dcl.type.elab] 155/// class-key ::[opt] nested-name-specifier[opt] identifier 156/// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] 157/// simple-template-id 158/// 159/// Note that the C++ class-specifier and elaborated-type-specifier, 160/// together, subsume the C99 struct-or-union-specifier: 161/// 162/// struct-or-union-specifier: [C99 6.7.2.1] 163/// struct-or-union identifier[opt] '{' struct-contents '}' 164/// struct-or-union identifier 165/// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents 166/// '}' attributes[opt] 167/// [GNU] struct-or-union attributes[opt] identifier 168/// struct-or-union: 169/// 'struct' 170/// 'union' 171void Parser::ParseClassSpecifier(DeclSpec &DS) { 172 assert((Tok.is(tok::kw_class) || 173 Tok.is(tok::kw_struct) || 174 Tok.is(tok::kw_union)) && 175 "Not a class specifier"); 176 DeclSpec::TST TagType = 177 Tok.is(tok::kw_class) ? DeclSpec::TST_class : 178 Tok.is(tok::kw_struct) ? DeclSpec::TST_struct : 179 DeclSpec::TST_union; 180 181 SourceLocation StartLoc = ConsumeToken(); 182 183 AttributeList *Attr = 0; 184 // If attributes exist after tag, parse them. 185 if (Tok.is(tok::kw___attribute)) 186 Attr = ParseAttributes(); 187 188 // FIXME: Parse the (optional) nested-name-specifier. 189 190 // Parse the (optional) class name. 191 // FIXME: Alternatively, parse a simple-template-id. 192 IdentifierInfo *Name = 0; 193 SourceLocation NameLoc; 194 if (Tok.is(tok::identifier)) { 195 Name = Tok.getIdentifierInfo(); 196 NameLoc = ConsumeToken(); 197 } 198 199 // There are three options here. If we have 'struct foo;', then 200 // this is a forward declaration. If we have 'struct foo {...' or 201 // 'struct fo :...' then this is a definition. Otherwise we have 202 // something like 'struct foo xyz', a reference. 203 Action::TagKind TK; 204 if (Tok.is(tok::l_brace) || (getLang().CPlusPlus && Tok.is(tok::colon))) 205 TK = Action::TK_Definition; 206 else if (Tok.is(tok::semi)) 207 TK = Action::TK_Declaration; 208 else 209 TK = Action::TK_Reference; 210 211 if (!Name && TK != Action::TK_Definition) { 212 // We have a declaration or reference to an anonymous class. 213 Diag(StartLoc, diag::err_anon_type_definition, 214 DeclSpec::getSpecifierName(TagType)); 215 216 // Skip the rest of this declarator, up until the comma or semicolon. 217 SkipUntil(tok::comma, true); 218 return; 219 } 220 221 // Parse the tag portion of this. 222 DeclTy *TagDecl = Actions.ActOnTag(CurScope, TagType, TK, StartLoc, Name, 223 NameLoc, Attr); 224 225 // Parse the optional base clause (C++ only). 226 if (getLang().CPlusPlus && Tok.is(tok::colon)) { 227 ParseBaseClause(TagDecl); 228 } 229 230 // If there is a body, parse it and inform the actions module. 231 if (Tok.is(tok::l_brace)) 232 // FIXME: Temporarily disable parsing for C++ classes until the Sema support 233 // is in place. 234 //if (getLang().CPlusPlus) 235 // ParseCXXMemberSpecification(StartLoc, TagType, TagDecl); 236 //else 237 ParseStructUnionBody(StartLoc, TagType, TagDecl); 238 else if (TK == Action::TK_Definition) { 239 // FIXME: Complain that we have a base-specifier list but no 240 // definition. 241 Diag(Tok.getLocation(), diag::err_expected_lbrace); 242 } 243 244 const char *PrevSpec = 0; 245 if (DS.SetTypeSpecType(TagType, StartLoc, PrevSpec, TagDecl)) 246 Diag(StartLoc, diag::err_invalid_decl_spec_combination, PrevSpec); 247} 248 249/// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. 250/// 251/// base-clause : [C++ class.derived] 252/// ':' base-specifier-list 253/// base-specifier-list: 254/// base-specifier '...'[opt] 255/// base-specifier-list ',' base-specifier '...'[opt] 256void Parser::ParseBaseClause(DeclTy *ClassDecl) 257{ 258 assert(Tok.is(tok::colon) && "Not a base clause"); 259 ConsumeToken(); 260 261 while (true) { 262 // Parse a base-specifier. 263 if (ParseBaseSpecifier(ClassDecl)) { 264 // Skip the rest of this base specifier, up until the comma or 265 // opening brace. 266 SkipUntil(tok::comma, tok::l_brace); 267 } 268 269 // If the next token is a comma, consume it and keep reading 270 // base-specifiers. 271 if (Tok.isNot(tok::comma)) break; 272 273 // Consume the comma. 274 ConsumeToken(); 275 } 276} 277 278/// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is 279/// one entry in the base class list of a class specifier, for example: 280/// class foo : public bar, virtual private baz { 281/// 'public bar' and 'virtual private baz' are each base-specifiers. 282/// 283/// base-specifier: [C++ class.derived] 284/// ::[opt] nested-name-specifier[opt] class-name 285/// 'virtual' access-specifier[opt] ::[opt] nested-name-specifier[opt] 286/// class-name 287/// access-specifier 'virtual'[opt] ::[opt] nested-name-specifier[opt] 288/// class-name 289bool Parser::ParseBaseSpecifier(DeclTy *ClassDecl) 290{ 291 bool IsVirtual = false; 292 SourceLocation StartLoc = Tok.getLocation(); 293 294 // Parse the 'virtual' keyword. 295 if (Tok.is(tok::kw_virtual)) { 296 ConsumeToken(); 297 IsVirtual = true; 298 } 299 300 // Parse an (optional) access specifier. 301 AccessSpecifier Access = getAccessSpecifierIfPresent(); 302 if (Access) 303 ConsumeToken(); 304 305 // Parse the 'virtual' keyword (again!), in case it came after the 306 // access specifier. 307 if (Tok.is(tok::kw_virtual)) { 308 SourceLocation VirtualLoc = ConsumeToken(); 309 if (IsVirtual) { 310 // Complain about duplicate 'virtual' 311 Diag(VirtualLoc, diag::err_dup_virtual); 312 } 313 314 IsVirtual = true; 315 } 316 317 // FIXME: Parse optional '::' and optional nested-name-specifier. 318 319 // Parse the class-name. 320 // FIXME: Alternatively, parse a simple-template-id. 321 if (Tok.isNot(tok::identifier)) { 322 Diag(Tok.getLocation(), diag::err_expected_class_name); 323 return true; 324 } 325 326 // We have an identifier; check whether it is actually a type. 327 DeclTy *BaseType = Actions.isTypeName(*Tok.getIdentifierInfo(), CurScope); 328 if (!BaseType) { 329 Diag(Tok.getLocation(), diag::err_expected_class_name); 330 return true; 331 } 332 333 // The location of the base class itself. 334 SourceLocation BaseLoc = Tok.getLocation(); 335 336 // Find the complete source range for the base-specifier. 337 SourceRange Range(StartLoc, BaseLoc); 338 339 // Consume the identifier token (finally!). 340 ConsumeToken(); 341 342 // Notify semantic analysis that we have parsed a complete 343 // base-specifier. 344 Actions.ActOnBaseSpecifier(ClassDecl, Range, IsVirtual, Access, BaseType, 345 BaseLoc); 346 return false; 347} 348 349/// getAccessSpecifierIfPresent - Determine whether the next token is 350/// a C++ access-specifier. 351/// 352/// access-specifier: [C++ class.derived] 353/// 'private' 354/// 'protected' 355/// 'public' 356AccessSpecifier Parser::getAccessSpecifierIfPresent() const 357{ 358 switch (Tok.getKind()) { 359 default: return AS_none; 360 case tok::kw_private: return AS_private; 361 case tok::kw_protected: return AS_protected; 362 case tok::kw_public: return AS_public; 363 } 364} 365 366/// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. 367/// 368/// member-declaration: 369/// decl-specifier-seq[opt] member-declarator-list[opt] ';' 370/// function-definition ';'[opt] 371/// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] 372/// using-declaration [TODO] 373/// [C++0x] static_assert-declaration [TODO] 374/// template-declaration [TODO] 375/// 376/// member-declarator-list: 377/// member-declarator 378/// member-declarator-list ',' member-declarator 379/// 380/// member-declarator: 381/// declarator pure-specifier[opt] 382/// declarator constant-initializer[opt] 383/// identifier[opt] ':' constant-expression 384/// 385/// pure-specifier: [TODO] 386/// '= 0' 387/// 388/// constant-initializer: 389/// '=' constant-expression 390/// 391Parser::DeclTy *Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS) { 392 SourceLocation DSStart = Tok.getLocation(); 393 // decl-specifier-seq: 394 // Parse the common declaration-specifiers piece. 395 DeclSpec DS; 396 ParseDeclarationSpecifiers(DS); 397 398 if (Tok.is(tok::semi)) { 399 ConsumeToken(); 400 // C++ 9.2p7: The member-declarator-list can be omitted only after a 401 // class-specifier or an enum-specifier or in a friend declaration. 402 // FIXME: Friend declarations. 403 switch (DS.getTypeSpecType()) { 404 case DeclSpec::TST_struct: 405 case DeclSpec::TST_union: 406 case DeclSpec::TST_class: 407 case DeclSpec::TST_enum: 408 return Actions.ParsedFreeStandingDeclSpec(CurScope, DS); 409 default: 410 Diag(DSStart, diag::err_no_declarators); 411 return 0; 412 } 413 } 414 415 // Parse the first declarator. 416 Declarator DeclaratorInfo(DS, Declarator::MemberContext); 417 ParseDeclarator(DeclaratorInfo); 418 // Error parsing the declarator? 419 if (DeclaratorInfo.getIdentifier() == 0) { 420 // If so, skip until the semi-colon or a }. 421 SkipUntil(tok::r_brace, true); 422 if (Tok.is(tok::semi)) 423 ConsumeToken(); 424 return 0; 425 } 426 427 // function-definition: 428 if (Tok.is(tok::l_brace)) { 429 if (!DeclaratorInfo.isFunctionDeclarator()) { 430 Diag(Tok, diag::err_func_def_no_params); 431 ConsumeBrace(); 432 SkipUntil(tok::r_brace, true); 433 return 0; 434 } 435 436 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 437 Diag(Tok, diag::err_function_declared_typedef); 438 // This recovery skips the entire function body. It would be nice 439 // to simply call ParseCXXInlineMethodDef() below, however Sema 440 // assumes the declarator represents a function, not a typedef. 441 ConsumeBrace(); 442 SkipUntil(tok::r_brace, true); 443 return 0; 444 } 445 446 return ParseCXXInlineMethodDef(AS, DeclaratorInfo); 447 } 448 449 // member-declarator-list: 450 // member-declarator 451 // member-declarator-list ',' member-declarator 452 453 DeclTy *LastDeclInGroup = 0; 454 ExprTy *BitfieldSize = 0; 455 ExprTy *Init = 0; 456 457 while (1) { 458 459 // member-declarator: 460 // declarator pure-specifier[opt] 461 // declarator constant-initializer[opt] 462 // identifier[opt] ':' constant-expression 463 464 if (Tok.is(tok::colon)) { 465 ConsumeToken(); 466 ExprResult Res = ParseConstantExpression(); 467 if (Res.isInvalid) 468 SkipUntil(tok::comma, true, true); 469 else 470 BitfieldSize = Res.Val; 471 } 472 473 // pure-specifier: 474 // '= 0' 475 // 476 // constant-initializer: 477 // '=' constant-expression 478 479 if (Tok.is(tok::equal)) { 480 ConsumeToken(); 481 ExprResult Res = ParseInitializer(); 482 if (Res.isInvalid) 483 SkipUntil(tok::comma, true, true); 484 else 485 Init = Res.Val; 486 } 487 488 // If attributes exist after the declarator, parse them. 489 if (Tok.is(tok::kw___attribute)) 490 DeclaratorInfo.AddAttributes(ParseAttributes()); 491 492 LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS, 493 DeclaratorInfo, 494 BitfieldSize, Init, 495 LastDeclInGroup); 496 497 // If we don't have a comma, it is either the end of the list (a ';') 498 // or an error, bail out. 499 if (Tok.isNot(tok::comma)) 500 break; 501 502 // Consume the comma. 503 ConsumeToken(); 504 505 // Parse the next declarator. 506 DeclaratorInfo.clear(); 507 BitfieldSize = Init = 0; 508 509 // Attributes are only allowed on the second declarator. 510 if (Tok.is(tok::kw___attribute)) 511 DeclaratorInfo.AddAttributes(ParseAttributes()); 512 513 ParseDeclarator(DeclaratorInfo); 514 } 515 516 if (Tok.is(tok::semi)) { 517 ConsumeToken(); 518 // Reverse the chain list. 519 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup); 520 } 521 522 Diag(Tok, diag::err_expected_semi_decl_list); 523 // Skip to end of block or statement 524 SkipUntil(tok::r_brace, true, true); 525 if (Tok.is(tok::semi)) 526 ConsumeToken(); 527 return 0; 528} 529 530/// ParseCXXMemberSpecification - Parse the class definition. 531/// 532/// member-specification: 533/// member-declaration member-specification[opt] 534/// access-specifier ':' member-specification[opt] 535/// 536void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 537 unsigned TagType, DeclTy *TagDecl) { 538 assert(TagType == DeclSpec::TST_struct || 539 TagType == DeclSpec::TST_union || 540 TagType == DeclSpec::TST_class && "Invalid TagType!"); 541 542 SourceLocation LBraceLoc = ConsumeBrace(); 543 544 if (!CurScope->isCXXClassScope() && // Not about to define a nested class. 545 CurScope->isInCXXInlineMethodScope()) { 546 // We will define a local class of an inline method. 547 // Push a new LexedMethodsForTopClass for its inline methods. 548 PushTopClassStack(); 549 } 550 551 // Enter a scope for the class. 552 EnterScope(Scope::CXXClassScope|Scope::DeclScope); 553 554 Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc); 555 556 // C++ 11p3: Members of a class defined with the keyword class are private 557 // by default. Members of a class defined with the keywords struct or union 558 // are public by default. 559 AccessSpecifier CurAS; 560 if (TagType == DeclSpec::TST_class) 561 CurAS = AS_private; 562 else 563 CurAS = AS_public; 564 565 // While we still have something to read, read the member-declarations. 566 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 567 // Each iteration of this loop reads one member-declaration. 568 569 // Check for extraneous top-level semicolon. 570 if (Tok.is(tok::semi)) { 571 Diag(Tok, diag::ext_extra_struct_semi); 572 ConsumeToken(); 573 continue; 574 } 575 576 AccessSpecifier AS = getAccessSpecifierIfPresent(); 577 if (AS != AS_none) { 578 // Current token is a C++ access specifier. 579 CurAS = AS; 580 ConsumeToken(); 581 ExpectAndConsume(tok::colon, diag::err_expected_colon); 582 continue; 583 } 584 585 // Parse all the comma separated declarators. 586 ParseCXXClassMemberDeclaration(CurAS); 587 } 588 589 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 590 591 AttributeList *AttrList = 0; 592 // If attributes exist after class contents, parse them. 593 if (Tok.is(tok::kw___attribute)) 594 AttrList = ParseAttributes(); // FIXME: where should I put them? 595 596 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl, 597 LBraceLoc, RBraceLoc); 598 599 // C++ 9.2p2: Within the class member-specification, the class is regarded as 600 // complete within function bodies, default arguments, 601 // exception-specifications, and constructor ctor-initializers (including 602 // such things in nested classes). 603 // 604 // FIXME: Only function bodies are parsed correctly, fix the rest. 605 if (!CurScope->getParent()->isCXXClassScope()) { 606 // We are not inside a nested class. This class and its nested classes 607 // are complete and we can parse the lexed inline method definitions. 608 ParseLexedMethodDefs(); 609 610 // For a local class of inline method, pop the LexedMethodsForTopClass that 611 // was previously pushed. 612 613 assert(CurScope->isInCXXInlineMethodScope() || 614 TopClassStacks.size() == 1 && 615 "MethodLexers not getting popped properly!"); 616 if (CurScope->isInCXXInlineMethodScope()) 617 PopTopClassStack(); 618 } 619 620 // Leave the class scope. 621 ExitScope(); 622 623 Actions.ActOnFinishCXXClassDef(TagDecl, RBraceLoc); 624} 625