SemaDeclCXX.cpp revision 60d62c29d260596454aaf4cb50cbc756ac08875e
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 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 semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/TypeOrdering.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Basic/Diagnostic.h" 21#include "clang/Parse/DeclSpec.h" 22#include "llvm/Support/Compiler.h" 23#include <algorithm> // for std::equal 24#include <map> 25 26using namespace clang; 27 28//===----------------------------------------------------------------------===// 29// CheckDefaultArgumentVisitor 30//===----------------------------------------------------------------------===// 31 32namespace { 33 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 34 /// the default argument of a parameter to determine whether it 35 /// contains any ill-formed subexpressions. For example, this will 36 /// diagnose the use of local variables or parameters within the 37 /// default argument expression. 38 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 39 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 40 Expr *DefaultArg; 41 Sema *S; 42 43 public: 44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 45 : DefaultArg(defarg), S(s) {} 46 47 bool VisitExpr(Expr *Node); 48 bool VisitDeclRefExpr(DeclRefExpr *DRE); 49 }; 50 51 /// VisitExpr - Visit all of the children of this expression. 52 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 53 bool IsInvalid = false; 54 for (Stmt::child_iterator I = Node->child_begin(), 55 E = Node->child_end(); I != E; ++I) 56 IsInvalid |= Visit(*I); 57 return IsInvalid; 58 } 59 60 /// VisitDeclRefExpr - Visit a reference to a declaration, to 61 /// determine whether this declaration can be used in the default 62 /// argument expression. 63 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 64 NamedDecl *Decl = DRE->getDecl(); 65 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 66 // C++ [dcl.fct.default]p9 67 // Default arguments are evaluated each time the function is 68 // called. The order of evaluation of function arguments is 69 // unspecified. Consequently, parameters of a function shall not 70 // be used in default argument expressions, even if they are not 71 // evaluated. Parameters of a function declared before a default 72 // argument expression are in scope and can hide namespace and 73 // class member names. 74 return S->Diag(DRE->getSourceRange().getBegin(), 75 diag::err_param_default_argument_references_param, 76 Param->getName(), DefaultArg->getSourceRange()); 77 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 78 // C++ [dcl.fct.default]p7 79 // Local variables shall not be used in default argument 80 // expressions. 81 if (VDecl->isBlockVarDecl()) 82 return S->Diag(DRE->getSourceRange().getBegin(), 83 diag::err_param_default_argument_references_local, 84 VDecl->getName(), DefaultArg->getSourceRange()); 85 } 86 87 // FIXME: when Clang has support for member functions, "this" 88 // will also need to be diagnosed. 89 90 return false; 91 } 92} 93 94/// ActOnParamDefaultArgument - Check whether the default argument 95/// provided for a function parameter is well-formed. If so, attach it 96/// to the parameter declaration. 97void 98Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 99 ExprTy *defarg) { 100 ParmVarDecl *Param = (ParmVarDecl *)param; 101 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 102 QualType ParamType = Param->getType(); 103 104 // Default arguments are only permitted in C++ 105 if (!getLangOptions().CPlusPlus) { 106 Diag(EqualLoc, diag::err_param_default_argument, 107 DefaultArg->getSourceRange()); 108 return; 109 } 110 111 // C++ [dcl.fct.default]p5 112 // A default argument expression is implicitly converted (clause 113 // 4) to the parameter type. The default argument expression has 114 // the same semantic constraints as the initializer expression in 115 // a declaration of a variable of the parameter type, using the 116 // copy-initialization semantics (8.5). 117 // 118 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics 119 // for C++ (since we want copy-initialization, not copy-assignment), 120 // but we don't have the right semantics implemented yet. Because of 121 // this, our error message is also very poor. 122 QualType DefaultArgType = DefaultArg->getType(); 123 Expr *DefaultArgPtr = DefaultArg.get(); 124 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType, 125 DefaultArgPtr); 126 if (DefaultArgPtr != DefaultArg.get()) { 127 DefaultArg.take(); 128 DefaultArg.reset(DefaultArgPtr); 129 } 130 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(), 131 ParamType, DefaultArgType, DefaultArg.get(), 132 "in default argument")) { 133 return; 134 } 135 136 // Check that the default argument is well-formed 137 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 138 if (DefaultArgChecker.Visit(DefaultArg.get())) 139 return; 140 141 // Okay: add the default argument to the parameter 142 Param->setDefaultArg(DefaultArg.take()); 143} 144 145/// CheckExtraCXXDefaultArguments - Check for any extra default 146/// arguments in the declarator, which is not a function declaration 147/// or definition and therefore is not permitted to have default 148/// arguments. This routine should be invoked for every declarator 149/// that is not a function declaration or definition. 150void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 151 // C++ [dcl.fct.default]p3 152 // A default argument expression shall be specified only in the 153 // parameter-declaration-clause of a function declaration or in a 154 // template-parameter (14.1). It shall not be specified for a 155 // parameter pack. If it is specified in a 156 // parameter-declaration-clause, it shall not occur within a 157 // declarator or abstract-declarator of a parameter-declaration. 158 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 159 DeclaratorChunk &chunk = D.getTypeObject(i); 160 if (chunk.Kind == DeclaratorChunk::Function) { 161 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 162 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 163 if (Param->getDefaultArg()) { 164 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc, 165 Param->getDefaultArg()->getSourceRange()); 166 Param->setDefaultArg(0); 167 } 168 } 169 } 170 } 171} 172 173// MergeCXXFunctionDecl - Merge two declarations of the same C++ 174// function, once we already know that they have the same 175// type. Subroutine of MergeFunctionDecl. 176FunctionDecl * 177Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 178 // C++ [dcl.fct.default]p4: 179 // 180 // For non-template functions, default arguments can be added in 181 // later declarations of a function in the same 182 // scope. Declarations in different scopes have completely 183 // distinct sets of default arguments. That is, declarations in 184 // inner scopes do not acquire default arguments from 185 // declarations in outer scopes, and vice versa. In a given 186 // function declaration, all parameters subsequent to a 187 // parameter with a default argument shall have default 188 // arguments supplied in this or previous declarations. A 189 // default argument shall not be redefined by a later 190 // declaration (not even to the same value). 191 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 192 ParmVarDecl *OldParam = Old->getParamDecl(p); 193 ParmVarDecl *NewParam = New->getParamDecl(p); 194 195 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 196 Diag(NewParam->getLocation(), 197 diag::err_param_default_argument_redefinition, 198 NewParam->getDefaultArg()->getSourceRange()); 199 Diag(OldParam->getLocation(), diag::err_previous_definition); 200 } else if (OldParam->getDefaultArg()) { 201 // Merge the old default argument into the new parameter 202 NewParam->setDefaultArg(OldParam->getDefaultArg()); 203 } 204 } 205 206 return New; 207} 208 209/// CheckCXXDefaultArguments - Verify that the default arguments for a 210/// function declaration are well-formed according to C++ 211/// [dcl.fct.default]. 212void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 213 unsigned NumParams = FD->getNumParams(); 214 unsigned p; 215 216 // Find first parameter with a default argument 217 for (p = 0; p < NumParams; ++p) { 218 ParmVarDecl *Param = FD->getParamDecl(p); 219 if (Param->getDefaultArg()) 220 break; 221 } 222 223 // C++ [dcl.fct.default]p4: 224 // In a given function declaration, all parameters 225 // subsequent to a parameter with a default argument shall 226 // have default arguments supplied in this or previous 227 // declarations. A default argument shall not be redefined 228 // by a later declaration (not even to the same value). 229 unsigned LastMissingDefaultArg = 0; 230 for(; p < NumParams; ++p) { 231 ParmVarDecl *Param = FD->getParamDecl(p); 232 if (!Param->getDefaultArg()) { 233 if (Param->getIdentifier()) 234 Diag(Param->getLocation(), 235 diag::err_param_default_argument_missing_name, 236 Param->getIdentifier()->getName()); 237 else 238 Diag(Param->getLocation(), 239 diag::err_param_default_argument_missing); 240 241 LastMissingDefaultArg = p; 242 } 243 } 244 245 if (LastMissingDefaultArg > 0) { 246 // Some default arguments were missing. Clear out all of the 247 // default arguments up to (and including) the last missing 248 // default argument, so that we leave the function parameters 249 // in a semantically valid state. 250 for (p = 0; p <= LastMissingDefaultArg; ++p) { 251 ParmVarDecl *Param = FD->getParamDecl(p); 252 if (Param->getDefaultArg()) { 253 delete Param->getDefaultArg(); 254 Param->setDefaultArg(0); 255 } 256 } 257 } 258} 259 260/// isCurrentClassName - Determine whether the identifier II is the 261/// name of the class type currently being defined. In the case of 262/// nested classes, this will only return true if II is the name of 263/// the innermost class. 264bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) { 265 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext)) 266 return &II == CurDecl->getIdentifier(); 267 else 268 return false; 269} 270 271/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 272/// one entry in the base class list of a class specifier, for 273/// example: 274/// class foo : public bar, virtual private baz { 275/// 'public bar' and 'virtual private baz' are each base-specifiers. 276Sema::BaseResult 277Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 278 bool Virtual, AccessSpecifier Access, 279 TypeTy *basetype, SourceLocation BaseLoc) { 280 RecordDecl *Decl = (RecordDecl*)classdecl; 281 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 282 283 // Base specifiers must be record types. 284 if (!BaseType->isRecordType()) { 285 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 286 return true; 287 } 288 289 // C++ [class.union]p1: 290 // A union shall not be used as a base class. 291 if (BaseType->isUnionType()) { 292 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 293 return true; 294 } 295 296 // C++ [class.union]p1: 297 // A union shall not have base classes. 298 if (Decl->isUnion()) { 299 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 300 SpecifierRange); 301 return true; 302 } 303 304 // C++ [class.derived]p2: 305 // The class-name in a base-specifier shall not be an incompletely 306 // defined class. 307 if (BaseType->isIncompleteType()) { 308 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 309 return true; 310 } 311 312 // Create the base specifier. 313 return new CXXBaseSpecifier(SpecifierRange, Virtual, 314 BaseType->isClassType(), Access, BaseType); 315} 316 317/// ActOnBaseSpecifiers - Attach the given base specifiers to the 318/// class, after checking whether there are any duplicate base 319/// classes. 320void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 321 unsigned NumBases) { 322 if (NumBases == 0) 323 return; 324 325 // Used to keep track of which base types we have already seen, so 326 // that we can properly diagnose redundant direct base types. Note 327 // that the key is always the unqualified canonical type of the base 328 // class. 329 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 330 331 // Copy non-redundant base specifiers into permanent storage. 332 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 333 unsigned NumGoodBases = 0; 334 for (unsigned idx = 0; idx < NumBases; ++idx) { 335 QualType NewBaseType 336 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 337 NewBaseType = NewBaseType.getUnqualifiedType(); 338 339 if (KnownBaseTypes[NewBaseType]) { 340 // C++ [class.mi]p3: 341 // A class shall not be specified as a direct base class of a 342 // derived class more than once. 343 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 344 diag::err_duplicate_base_class, 345 KnownBaseTypes[NewBaseType]->getType().getAsString(), 346 BaseSpecs[idx]->getSourceRange()); 347 348 // Delete the duplicate base class specifier; we're going to 349 // overwrite its pointer later. 350 delete BaseSpecs[idx]; 351 } else { 352 // Okay, add this new base class. 353 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 354 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 355 } 356 } 357 358 // Attach the remaining base class specifiers to the derived class. 359 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 360 Decl->setBases(BaseSpecs, NumGoodBases); 361 362 // Delete the remaining (good) base class specifiers, since their 363 // data has been copied into the CXXRecordDecl. 364 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 365 delete BaseSpecs[idx]; 366} 367 368//===----------------------------------------------------------------------===// 369// C++ class member Handling 370//===----------------------------------------------------------------------===// 371 372/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 373/// definition, when on C++. 374void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 375 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 376 PushDeclContext(Dcl); 377 FieldCollector->StartClass(); 378 379 if (Dcl->getIdentifier()) { 380 // C++ [class]p2: 381 // [...] The class-name is also inserted into the scope of the 382 // class itself; this is known as the injected-class-name. For 383 // purposes of access checking, the injected-class-name is treated 384 // as if it were a public member name. 385 TypedefDecl *InjectedClassName 386 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(), 387 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0); 388 PushOnScopeChains(InjectedClassName, S); 389 } 390} 391 392/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 393/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 394/// bitfield width if there is one and 'InitExpr' specifies the initializer if 395/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 396/// declarators on it. 397/// 398/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 399/// an instance field is declared, a new CXXFieldDecl is created but the method 400/// does *not* return it; it returns LastInGroup instead. The other C++ members 401/// (which are all ScopedDecls) are returned after appending them to 402/// LastInGroup. 403Sema::DeclTy * 404Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 405 ExprTy *BW, ExprTy *InitExpr, 406 DeclTy *LastInGroup) { 407 const DeclSpec &DS = D.getDeclSpec(); 408 IdentifierInfo *II = D.getIdentifier(); 409 Expr *BitWidth = static_cast<Expr*>(BW); 410 Expr *Init = static_cast<Expr*>(InitExpr); 411 SourceLocation Loc = D.getIdentifierLoc(); 412 413 // C++ 9.2p6: A member shall not be declared to have automatic storage 414 // duration (auto, register) or with the extern storage-class-specifier. 415 switch (DS.getStorageClassSpec()) { 416 case DeclSpec::SCS_unspecified: 417 case DeclSpec::SCS_typedef: 418 case DeclSpec::SCS_static: 419 // FALL THROUGH. 420 break; 421 default: 422 if (DS.getStorageClassSpecLoc().isValid()) 423 Diag(DS.getStorageClassSpecLoc(), 424 diag::err_storageclass_invalid_for_member); 425 else 426 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 427 D.getMutableDeclSpec().ClearStorageClassSpecs(); 428 } 429 430 bool isFunc = D.isFunctionDeclarator(); 431 if (!isFunc && 432 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 433 D.getNumTypeObjects() == 0) { 434 // Check also for this case: 435 // 436 // typedef int f(); 437 // f a; 438 // 439 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 440 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 441 } 442 443 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 444 !isFunc); 445 446 Decl *Member; 447 bool InvalidDecl = false; 448 449 if (isInstField) 450 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 451 else 452 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 453 454 if (!Member) return LastInGroup; 455 456 assert((II || isInstField) && "No identifier for non-field ?"); 457 458 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 459 // specific methods. Use a wrapper class that can be used with all C++ class 460 // member decls. 461 CXXClassMemberWrapper(Member).setAccess(AS); 462 463 if (BitWidth) { 464 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 465 // constant-expression be a value equal to zero. 466 // FIXME: Check this. 467 468 if (D.isFunctionDeclarator()) { 469 // FIXME: Emit diagnostic about only constructors taking base initializers 470 // or something similar, when constructor support is in place. 471 Diag(Loc, diag::err_not_bitfield_type, 472 II->getName(), BitWidth->getSourceRange()); 473 InvalidDecl = true; 474 475 } else if (isInstField) { 476 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 477 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 478 Diag(Loc, diag::err_not_integral_type_bitfield, 479 II->getName(), BitWidth->getSourceRange()); 480 InvalidDecl = true; 481 } 482 483 } else if (isa<FunctionDecl>(Member)) { 484 // A function typedef ("typedef int f(); f a;"). 485 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 486 Diag(Loc, diag::err_not_integral_type_bitfield, 487 II->getName(), BitWidth->getSourceRange()); 488 InvalidDecl = true; 489 490 } else if (isa<TypedefDecl>(Member)) { 491 // "cannot declare 'A' to be a bit-field type" 492 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 493 BitWidth->getSourceRange()); 494 InvalidDecl = true; 495 496 } else { 497 assert(isa<CXXClassVarDecl>(Member) && 498 "Didn't we cover all member kinds?"); 499 // C++ 9.6p3: A bit-field shall not be a static member. 500 // "static member 'A' cannot be a bit-field" 501 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 502 BitWidth->getSourceRange()); 503 InvalidDecl = true; 504 } 505 } 506 507 if (Init) { 508 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 509 // if it declares a static member of const integral or const enumeration 510 // type. 511 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 512 // ...static member of... 513 CVD->setInit(Init); 514 // ...const integral or const enumeration type. 515 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 516 CVD->getType()->isIntegralType()) { 517 // constant-initializer 518 if (CheckForConstantInitializer(Init, CVD->getType())) 519 InvalidDecl = true; 520 521 } else { 522 // not const integral. 523 Diag(Loc, diag::err_member_initialization, 524 II->getName(), Init->getSourceRange()); 525 InvalidDecl = true; 526 } 527 528 } else { 529 // not static member. 530 Diag(Loc, diag::err_member_initialization, 531 II->getName(), Init->getSourceRange()); 532 InvalidDecl = true; 533 } 534 } 535 536 if (InvalidDecl) 537 Member->setInvalidDecl(); 538 539 if (isInstField) { 540 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 541 return LastInGroup; 542 } 543 return Member; 544} 545 546void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 547 DeclTy *TagDecl, 548 SourceLocation LBrac, 549 SourceLocation RBrac) { 550 ActOnFields(S, RLoc, TagDecl, 551 (DeclTy**)FieldCollector->getCurFields(), 552 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 553} 554 555void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 556 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 557 FieldCollector->FinishClass(); 558 PopDeclContext(); 559 560 // Everything, including inline method definitions, have been parsed. 561 // Let the consumer know of the new TagDecl definition. 562 Consumer.HandleTagDeclDefinition(Rec); 563} 564 565/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 566/// the declaration of the given C++ constructor ConDecl that was 567/// built from declarator D. This routine is responsible for checking 568/// that the newly-created constructor declaration is well-formed and 569/// for recording it in the C++ class. Example: 570/// 571/// @code 572/// class X { 573/// X(); // X::X() will be the ConDecl. 574/// }; 575/// @endcode 576Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 577 assert(ConDecl && "Expected to receive a constructor declaration"); 578 579 // Check default arguments on the constructor 580 CheckCXXDefaultArguments(ConDecl); 581 582 // FIXME: Make sure this constructor is an overload of the existing 583 // constructors and update the class to reflect the addition of this 584 // constructor (e.g., it now has a user-defined constructor, might 585 // have a user-declared copy constructor, etc.). 586 587 // Add this constructor to the set of constructors of the current 588 // class. 589 if (CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext)) { 590 ClassDecl->addConstructor(ConDecl); 591 } else { 592 assert(false && "Cannot add a constructor if we're not in the class!"); 593 } 594 595 596 return (DeclTy *)ConDecl; 597} 598 599//===----------------------------------------------------------------------===// 600// Namespace Handling 601//===----------------------------------------------------------------------===// 602 603/// ActOnStartNamespaceDef - This is called at the start of a namespace 604/// definition. 605Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 606 SourceLocation IdentLoc, 607 IdentifierInfo *II, 608 SourceLocation LBrace) { 609 NamespaceDecl *Namespc = 610 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 611 Namespc->setLBracLoc(LBrace); 612 613 Scope *DeclRegionScope = NamespcScope->getParent(); 614 615 if (II) { 616 // C++ [namespace.def]p2: 617 // The identifier in an original-namespace-definition shall not have been 618 // previously defined in the declarative region in which the 619 // original-namespace-definition appears. The identifier in an 620 // original-namespace-definition is the name of the namespace. Subsequently 621 // in that declarative region, it is treated as an original-namespace-name. 622 623 Decl *PrevDecl = 624 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 625 /*enableLazyBuiltinCreation=*/false); 626 627 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 628 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 629 // This is an extended namespace definition. 630 // Attach this namespace decl to the chain of extended namespace 631 // definitions. 632 NamespaceDecl *NextNS = OrigNS; 633 while (NextNS->getNextNamespace()) 634 NextNS = NextNS->getNextNamespace(); 635 636 NextNS->setNextNamespace(Namespc); 637 Namespc->setOriginalNamespace(OrigNS); 638 639 // We won't add this decl to the current scope. We want the namespace 640 // name to return the original namespace decl during a name lookup. 641 } else { 642 // This is an invalid name redefinition. 643 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 644 Namespc->getName()); 645 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 646 Namespc->setInvalidDecl(); 647 // Continue on to push Namespc as current DeclContext and return it. 648 } 649 } else { 650 // This namespace name is declared for the first time. 651 PushOnScopeChains(Namespc, DeclRegionScope); 652 } 653 } 654 else { 655 // FIXME: Handle anonymous namespaces 656 } 657 658 // Although we could have an invalid decl (i.e. the namespace name is a 659 // redefinition), push it as current DeclContext and try to continue parsing. 660 PushDeclContext(Namespc->getOriginalNamespace()); 661 return Namespc; 662} 663 664/// ActOnFinishNamespaceDef - This callback is called after a namespace is 665/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 666void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 667 Decl *Dcl = static_cast<Decl *>(D); 668 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 669 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 670 Namespc->setRBracLoc(RBrace); 671 PopDeclContext(); 672} 673 674 675/// AddCXXDirectInitializerToDecl - This action is called immediately after 676/// ActOnDeclarator, when a C++ direct initializer is present. 677/// e.g: "int x(1);" 678void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 679 ExprTy **ExprTys, unsigned NumExprs, 680 SourceLocation *CommaLocs, 681 SourceLocation RParenLoc) { 682 assert(NumExprs != 0 && ExprTys && "missing expressions"); 683 Decl *RealDecl = static_cast<Decl *>(Dcl); 684 685 // If there is no declaration, there was an error parsing it. Just ignore 686 // the initializer. 687 if (RealDecl == 0) { 688 for (unsigned i = 0; i != NumExprs; ++i) 689 delete static_cast<Expr *>(ExprTys[i]); 690 return; 691 } 692 693 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 694 if (!VDecl) { 695 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 696 RealDecl->setInvalidDecl(); 697 return; 698 } 699 700 // We will treat direct-initialization as a copy-initialization: 701 // int x(1); -as-> int x = 1; 702 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 703 // 704 // Clients that want to distinguish between the two forms, can check for 705 // direct initializer using VarDecl::hasCXXDirectInitializer(). 706 // A major benefit is that clients that don't particularly care about which 707 // exactly form was it (like the CodeGen) can handle both cases without 708 // special case code. 709 710 // C++ 8.5p11: 711 // The form of initialization (using parentheses or '=') is generally 712 // insignificant, but does matter when the entity being initialized has a 713 // class type. 714 715 if (VDecl->getType()->isRecordType()) { 716 // FIXME: When constructors for class types are supported, determine how 717 // exactly semantic checking will be done for direct initializers. 718 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error, 719 "initialization for class types is not handled yet"); 720 Diag(VDecl->getLocation(), DiagID); 721 RealDecl->setInvalidDecl(); 722 return; 723 } 724 725 if (NumExprs > 1) { 726 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg, 727 SourceRange(VDecl->getLocation(), RParenLoc)); 728 RealDecl->setInvalidDecl(); 729 return; 730 } 731 732 // Let clients know that initialization was done with a direct initializer. 733 VDecl->setCXXDirectInitializer(true); 734 735 assert(NumExprs == 1 && "Expected 1 expression"); 736 // Set the init expression, handles conversions. 737 AddInitializerToDecl(Dcl, ExprTys[0]); 738} 739 740/// CompareReferenceRelationship - Compare the two types T1 and T2 to 741/// determine whether they are reference-related, 742/// reference-compatible, reference-compatible with added 743/// qualification, or incompatible, for use in C++ initialization by 744/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 745/// type, and the first type (T1) is the pointee type of the reference 746/// type being initialized. 747Sema::ReferenceCompareResult 748Sema::CompareReferenceRelationship(QualType T1, QualType T2, 749 bool& DerivedToBase) { 750 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 751 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 752 753 T1 = Context.getCanonicalType(T1); 754 T2 = Context.getCanonicalType(T2); 755 QualType UnqualT1 = T1.getUnqualifiedType(); 756 QualType UnqualT2 = T2.getUnqualifiedType(); 757 758 // C++ [dcl.init.ref]p4: 759 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 760 // reference-related to “cv2 T2” if T1 is the same type as T2, or 761 // T1 is a base class of T2. 762 if (UnqualT1 == UnqualT2) 763 DerivedToBase = false; 764 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 765 DerivedToBase = true; 766 else 767 return Ref_Incompatible; 768 769 // At this point, we know that T1 and T2 are reference-related (at 770 // least). 771 772 // C++ [dcl.init.ref]p4: 773 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 774 // reference-related to T2 and cv1 is the same cv-qualification 775 // as, or greater cv-qualification than, cv2. For purposes of 776 // overload resolution, cases for which cv1 is greater 777 // cv-qualification than cv2 are identified as 778 // reference-compatible with added qualification (see 13.3.3.2). 779 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 780 return Ref_Compatible; 781 else if (T1.isMoreQualifiedThan(T2)) 782 return Ref_Compatible_With_Added_Qualification; 783 else 784 return Ref_Related; 785} 786 787/// CheckReferenceInit - Check the initialization of a reference 788/// variable with the given initializer (C++ [dcl.init.ref]). Init is 789/// the initializer (either a simple initializer or an initializer 790/// list), and DeclType is the type of the declaration. When ICS is 791/// non-null, this routine will compute the implicit conversion 792/// sequence according to C++ [over.ics.ref] and will not produce any 793/// diagnostics; when ICS is null, it will emit diagnostics when any 794/// errors are found. Either way, a return value of true indicates 795/// that there was a failure, a return value of false indicates that 796/// the reference initialization succeeded. 797bool 798Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 799 ImplicitConversionSequence *ICS) { 800 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 801 802 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 803 QualType T2 = Init->getType(); 804 805 // Compute some basic properties of the types and the initializer. 806 bool DerivedToBase = false; 807 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 808 ReferenceCompareResult RefRelationship 809 = CompareReferenceRelationship(T1, T2, DerivedToBase); 810 811 // Most paths end in a failed conversion. 812 if (ICS) 813 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 814 815 // C++ [dcl.init.ref]p5: 816 // A reference to type “cv1 T1” is initialized by an expression 817 // of type “cv2 T2” as follows: 818 819 // -- If the initializer expression 820 821 bool BindsDirectly = false; 822 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 823 // reference-compatible with “cv2 T2,” or 824 // 825 // Note that the bit-field check is skipped if we are just computing 826 // the implicit conversion sequence (C++ [over.best.ics]p2). 827 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 828 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 829 BindsDirectly = true; 830 831 if (ICS) { 832 // C++ [over.ics.ref]p1: 833 // When a parameter of reference type binds directly (8.5.3) 834 // to an argument expression, the implicit conversion sequence 835 // is the identity conversion, unless the argument expression 836 // has a type that is a derived class of the parameter type, 837 // in which case the implicit conversion sequence is a 838 // derived-to-base Conversion (13.3.3.1). 839 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 840 ICS->Standard.First = ICK_Identity; 841 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 842 ICS->Standard.Third = ICK_Identity; 843 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 844 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 845 ICS->Standard.ReferenceBinding = true; 846 ICS->Standard.DirectBinding = true; 847 848 // Nothing more to do: the inaccessibility/ambiguity check for 849 // derived-to-base conversions is suppressed when we're 850 // computing the implicit conversion sequence (C++ 851 // [over.best.ics]p2). 852 return false; 853 } else { 854 // Perform the conversion. 855 // FIXME: Binding to a subobject of the lvalue is going to require 856 // more AST annotation than this. 857 ImpCastExprToType(Init, T1); 858 } 859 } 860 861 // -- has a class type (i.e., T2 is a class type) and can be 862 // implicitly converted to an lvalue of type “cv3 T3,” 863 // where “cv1 T1” is reference-compatible with “cv3 T3” 864 // 92) (this conversion is selected by enumerating the 865 // applicable conversion functions (13.3.1.6) and choosing 866 // the best one through overload resolution (13.3)), 867 // FIXME: Implement this second bullet, once we have conversion 868 // functions. Also remember C++ [over.ics.ref]p1, second part. 869 870 if (BindsDirectly) { 871 // C++ [dcl.init.ref]p4: 872 // [...] In all cases where the reference-related or 873 // reference-compatible relationship of two types is used to 874 // establish the validity of a reference binding, and T1 is a 875 // base class of T2, a program that necessitates such a binding 876 // is ill-formed if T1 is an inaccessible (clause 11) or 877 // ambiguous (10.2) base class of T2. 878 // 879 // Note that we only check this condition when we're allowed to 880 // complain about errors, because we should not be checking for 881 // ambiguity (or inaccessibility) unless the reference binding 882 // actually happens. 883 if (DerivedToBase) 884 return CheckDerivedToBaseConversion(T2, T1, 885 Init->getSourceRange().getBegin(), 886 Init->getSourceRange()); 887 else 888 return false; 889 } 890 891 // -- Otherwise, the reference shall be to a non-volatile const 892 // type (i.e., cv1 shall be const). 893 if (T1.getCVRQualifiers() != QualType::Const) { 894 if (!ICS) 895 Diag(Init->getSourceRange().getBegin(), 896 diag::err_not_reference_to_const_init, 897 T1.getAsString(), 898 InitLvalue != Expr::LV_Valid? "temporary" : "value", 899 T2.getAsString(), Init->getSourceRange()); 900 return true; 901 } 902 903 // -- If the initializer expression is an rvalue, with T2 a 904 // class type, and “cv1 T1” is reference-compatible with 905 // “cv2 T2,” the reference is bound in one of the 906 // following ways (the choice is implementation-defined): 907 // 908 // -- The reference is bound to the object represented by 909 // the rvalue (see 3.10) or to a sub-object within that 910 // object. 911 // 912 // -- A temporary of type “cv1 T2” [sic] is created, and 913 // a constructor is called to copy the entire rvalue 914 // object into the temporary. The reference is bound to 915 // the temporary or to a sub-object within the 916 // temporary. 917 // 918 // 919 // The constructor that would be used to make the copy 920 // shall be callable whether or not the copy is actually 921 // done. 922 // 923 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 924 // freedom, so we will always take the first option and never build 925 // a temporary in this case. FIXME: We will, however, have to check 926 // for the presence of a copy constructor in C++98/03 mode. 927 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 928 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 929 if (ICS) { 930 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 931 ICS->Standard.First = ICK_Identity; 932 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 933 ICS->Standard.Third = ICK_Identity; 934 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 935 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 936 ICS->Standard.ReferenceBinding = true; 937 ICS->Standard.DirectBinding = false; 938 } else { 939 // FIXME: Binding to a subobject of the rvalue is going to require 940 // more AST annotation than this. 941 ImpCastExprToType(Init, T1); 942 } 943 return false; 944 } 945 946 // -- Otherwise, a temporary of type “cv1 T1” is created and 947 // initialized from the initializer expression using the 948 // rules for a non-reference copy initialization (8.5). The 949 // reference is then bound to the temporary. If T1 is 950 // reference-related to T2, cv1 must be the same 951 // cv-qualification as, or greater cv-qualification than, 952 // cv2; otherwise, the program is ill-formed. 953 if (RefRelationship == Ref_Related) { 954 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 955 // we would be reference-compatible or reference-compatible with 956 // added qualification. But that wasn't the case, so the reference 957 // initialization fails. 958 if (!ICS) 959 Diag(Init->getSourceRange().getBegin(), 960 diag::err_reference_init_drops_quals, 961 T1.getAsString(), 962 InitLvalue != Expr::LV_Valid? "temporary" : "value", 963 T2.getAsString(), Init->getSourceRange()); 964 return true; 965 } 966 967 // Actually try to convert the initializer to T1. 968 if (ICS) { 969 /// C++ [over.ics.ref]p2: 970 /// 971 /// When a parameter of reference type is not bound directly to 972 /// an argument expression, the conversion sequence is the one 973 /// required to convert the argument expression to the 974 /// underlying type of the reference according to 975 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 976 /// to copy-initializing a temporary of the underlying type with 977 /// the argument expression. Any difference in top-level 978 /// cv-qualification is subsumed by the initialization itself 979 /// and does not constitute a conversion. 980 *ICS = TryImplicitConversion(Init, T1); 981 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 982 } else { 983 return PerformImplicitConversion(Init, T1); 984 } 985} 986