ParseDeclCXX.cpp revision 3a9fdb4742b21c0a3c27f18c5e4e94bab6f9e64c
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 Declarator DeclaratorInfo(DS, Declarator::MemberContext); 416 417 if (Tok.isNot(tok::colon)) { 418 // Parse the first declarator. 419 ParseDeclarator(DeclaratorInfo); 420 // Error parsing the declarator? 421 if (DeclaratorInfo.getIdentifier() == 0) { 422 // If so, skip until the semi-colon or a }. 423 SkipUntil(tok::r_brace, true); 424 if (Tok.is(tok::semi)) 425 ConsumeToken(); 426 return 0; 427 } 428 429 // function-definition: 430 if (Tok.is(tok::l_brace)) { 431 if (!DeclaratorInfo.isFunctionDeclarator()) { 432 Diag(Tok, diag::err_func_def_no_params); 433 ConsumeBrace(); 434 SkipUntil(tok::r_brace, true); 435 return 0; 436 } 437 438 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { 439 Diag(Tok, diag::err_function_declared_typedef); 440 // This recovery skips the entire function body. It would be nice 441 // to simply call ParseCXXInlineMethodDef() below, however Sema 442 // assumes the declarator represents a function, not a typedef. 443 ConsumeBrace(); 444 SkipUntil(tok::r_brace, true); 445 return 0; 446 } 447 448 return ParseCXXInlineMethodDef(AS, DeclaratorInfo); 449 } 450 } 451 452 // member-declarator-list: 453 // member-declarator 454 // member-declarator-list ',' member-declarator 455 456 DeclTy *LastDeclInGroup = 0; 457 ExprTy *BitfieldSize = 0; 458 ExprTy *Init = 0; 459 460 while (1) { 461 462 // member-declarator: 463 // declarator pure-specifier[opt] 464 // declarator constant-initializer[opt] 465 // identifier[opt] ':' constant-expression 466 467 if (Tok.is(tok::colon)) { 468 ConsumeToken(); 469 ExprResult Res = ParseConstantExpression(); 470 if (Res.isInvalid) 471 SkipUntil(tok::comma, true, true); 472 else 473 BitfieldSize = Res.Val; 474 } 475 476 // pure-specifier: 477 // '= 0' 478 // 479 // constant-initializer: 480 // '=' constant-expression 481 482 if (Tok.is(tok::equal)) { 483 ConsumeToken(); 484 ExprResult Res = ParseInitializer(); 485 if (Res.isInvalid) 486 SkipUntil(tok::comma, true, true); 487 else 488 Init = Res.Val; 489 } 490 491 // If attributes exist after the declarator, parse them. 492 if (Tok.is(tok::kw___attribute)) 493 DeclaratorInfo.AddAttributes(ParseAttributes()); 494 495 LastDeclInGroup = Actions.ActOnCXXMemberDeclarator(CurScope, AS, 496 DeclaratorInfo, 497 BitfieldSize, Init, 498 LastDeclInGroup); 499 500 // If we don't have a comma, it is either the end of the list (a ';') 501 // or an error, bail out. 502 if (Tok.isNot(tok::comma)) 503 break; 504 505 // Consume the comma. 506 ConsumeToken(); 507 508 // Parse the next declarator. 509 DeclaratorInfo.clear(); 510 BitfieldSize = Init = 0; 511 512 // Attributes are only allowed on the second declarator. 513 if (Tok.is(tok::kw___attribute)) 514 DeclaratorInfo.AddAttributes(ParseAttributes()); 515 516 if (Tok.isNot(tok::colon)) 517 ParseDeclarator(DeclaratorInfo); 518 } 519 520 if (Tok.is(tok::semi)) { 521 ConsumeToken(); 522 // Reverse the chain list. 523 return Actions.FinalizeDeclaratorGroup(CurScope, LastDeclInGroup); 524 } 525 526 Diag(Tok, diag::err_expected_semi_decl_list); 527 // Skip to end of block or statement 528 SkipUntil(tok::r_brace, true, true); 529 if (Tok.is(tok::semi)) 530 ConsumeToken(); 531 return 0; 532} 533 534/// ParseCXXMemberSpecification - Parse the class definition. 535/// 536/// member-specification: 537/// member-declaration member-specification[opt] 538/// access-specifier ':' member-specification[opt] 539/// 540void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, 541 unsigned TagType, DeclTy *TagDecl) { 542 assert(TagType == DeclSpec::TST_struct || 543 TagType == DeclSpec::TST_union || 544 TagType == DeclSpec::TST_class && "Invalid TagType!"); 545 546 SourceLocation LBraceLoc = ConsumeBrace(); 547 548 if (!CurScope->isCXXClassScope() && // Not about to define a nested class. 549 CurScope->isInCXXInlineMethodScope()) { 550 // We will define a local class of an inline method. 551 // Push a new LexedMethodsForTopClass for its inline methods. 552 PushTopClassStack(); 553 } 554 555 // Enter a scope for the class. 556 EnterScope(Scope::CXXClassScope|Scope::DeclScope); 557 558 Actions.ActOnStartCXXClassDef(CurScope, TagDecl, LBraceLoc); 559 560 // C++ 11p3: Members of a class defined with the keyword class are private 561 // by default. Members of a class defined with the keywords struct or union 562 // are public by default. 563 AccessSpecifier CurAS; 564 if (TagType == DeclSpec::TST_class) 565 CurAS = AS_private; 566 else 567 CurAS = AS_public; 568 569 // While we still have something to read, read the member-declarations. 570 while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { 571 // Each iteration of this loop reads one member-declaration. 572 573 // Check for extraneous top-level semicolon. 574 if (Tok.is(tok::semi)) { 575 Diag(Tok, diag::ext_extra_struct_semi); 576 ConsumeToken(); 577 continue; 578 } 579 580 AccessSpecifier AS = getAccessSpecifierIfPresent(); 581 if (AS != AS_none) { 582 // Current token is a C++ access specifier. 583 CurAS = AS; 584 ConsumeToken(); 585 ExpectAndConsume(tok::colon, diag::err_expected_colon); 586 continue; 587 } 588 589 // Parse all the comma separated declarators. 590 ParseCXXClassMemberDeclaration(CurAS); 591 } 592 593 SourceLocation RBraceLoc = MatchRHSPunctuation(tok::r_brace, LBraceLoc); 594 595 AttributeList *AttrList = 0; 596 // If attributes exist after class contents, parse them. 597 if (Tok.is(tok::kw___attribute)) 598 AttrList = ParseAttributes(); // FIXME: where should I put them? 599 600 Actions.ActOnFinishCXXMemberSpecification(CurScope, RecordLoc, TagDecl, 601 LBraceLoc, RBraceLoc); 602 603 // C++ 9.2p2: Within the class member-specification, the class is regarded as 604 // complete within function bodies, default arguments, 605 // exception-specifications, and constructor ctor-initializers (including 606 // such things in nested classes). 607 // 608 // FIXME: Only function bodies are parsed correctly, fix the rest. 609 if (!CurScope->getParent()->isCXXClassScope()) { 610 // We are not inside a nested class. This class and its nested classes 611 // are complete and we can parse the lexed inline method definitions. 612 ParseLexedMethodDefs(); 613 614 // For a local class of inline method, pop the LexedMethodsForTopClass that 615 // was previously pushed. 616 617 assert(CurScope->isInCXXInlineMethodScope() || 618 TopClassStacks.size() == 1 && 619 "MethodLexers not getting popped properly!"); 620 if (CurScope->isInCXXInlineMethodScope()) 621 PopTopClassStack(); 622 } 623 624 // Leave the class scope. 625 ExitScope(); 626 627 Actions.ActOnFinishCXXClassDef(TagDecl, RBraceLoc); 628} 629