SemaDeclCXX.cpp revision 1cd1b1e987f5e2f060d7972b13d83239b36d77d6
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 "SemaInherit.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/TypeOrdering.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Parse/DeclSpec.h" 23#include "llvm/Support/Compiler.h" 24#include <algorithm> // for std::equal 25#include <map> 26 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// CheckDefaultArgumentVisitor 31//===----------------------------------------------------------------------===// 32 33namespace { 34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 35 /// the default argument of a parameter to determine whether it 36 /// contains any ill-formed subexpressions. For example, this will 37 /// diagnose the use of local variables or parameters within the 38 /// default argument expression. 39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 40 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 41 Expr *DefaultArg; 42 Sema *S; 43 44 public: 45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 46 : DefaultArg(defarg), S(s) {} 47 48 bool VisitExpr(Expr *Node); 49 bool VisitDeclRefExpr(DeclRefExpr *DRE); 50 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 51 }; 52 53 /// VisitExpr - Visit all of the children of this expression. 54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 55 bool IsInvalid = false; 56 for (Stmt::child_iterator I = Node->child_begin(), 57 E = Node->child_end(); I != E; ++I) 58 IsInvalid |= Visit(*I); 59 return IsInvalid; 60 } 61 62 /// VisitDeclRefExpr - Visit a reference to a declaration, to 63 /// determine whether this declaration can be used in the default 64 /// argument expression. 65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 66 NamedDecl *Decl = DRE->getDecl(); 67 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 68 // C++ [dcl.fct.default]p9 69 // Default arguments are evaluated each time the function is 70 // called. The order of evaluation of function arguments is 71 // unspecified. Consequently, parameters of a function shall not 72 // be used in default argument expressions, even if they are not 73 // evaluated. Parameters of a function declared before a default 74 // argument expression are in scope and can hide namespace and 75 // class member names. 76 return S->Diag(DRE->getSourceRange().getBegin(), 77 diag::err_param_default_argument_references_param, 78 Param->getName(), DefaultArg->getSourceRange()); 79 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 80 // C++ [dcl.fct.default]p7 81 // Local variables shall not be used in default argument 82 // expressions. 83 if (VDecl->isBlockVarDecl()) 84 return S->Diag(DRE->getSourceRange().getBegin(), 85 diag::err_param_default_argument_references_local, 86 VDecl->getName(), DefaultArg->getSourceRange()); 87 } 88 89 return false; 90 } 91 92 /// VisitCXXThisExpr - Visit a C++ "this" expression. 93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 94 // C++ [dcl.fct.default]p8: 95 // The keyword this shall not be used in a default argument of a 96 // member function. 97 return S->Diag(ThisE->getSourceRange().getBegin(), 98 diag::err_param_default_argument_references_this, 99 ThisE->getSourceRange()); 100 } 101} 102 103/// ActOnParamDefaultArgument - Check whether the default argument 104/// provided for a function parameter is well-formed. If so, attach it 105/// to the parameter declaration. 106void 107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 108 ExprTy *defarg) { 109 ParmVarDecl *Param = (ParmVarDecl *)param; 110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 111 QualType ParamType = Param->getType(); 112 113 // Default arguments are only permitted in C++ 114 if (!getLangOptions().CPlusPlus) { 115 Diag(EqualLoc, diag::err_param_default_argument, 116 DefaultArg->getSourceRange()); 117 return; 118 } 119 120 // C++ [dcl.fct.default]p5 121 // A default argument expression is implicitly converted (clause 122 // 4) to the parameter type. The default argument expression has 123 // the same semantic constraints as the initializer expression in 124 // a declaration of a variable of the parameter type, using the 125 // copy-initialization semantics (8.5). 126 Expr *DefaultArgPtr = DefaultArg.get(); 127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType, 128 "in default argument"); 129 if (DefaultArgPtr != DefaultArg.get()) { 130 DefaultArg.take(); 131 DefaultArg.reset(DefaultArgPtr); 132 } 133 if (DefaultInitFailed) { 134 return; 135 } 136 137 // Check that the default argument is well-formed 138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 139 if (DefaultArgChecker.Visit(DefaultArg.get())) 140 return; 141 142 // Okay: add the default argument to the parameter 143 Param->setDefaultArg(DefaultArg.take()); 144} 145 146/// CheckExtraCXXDefaultArguments - Check for any extra default 147/// arguments in the declarator, which is not a function declaration 148/// or definition and therefore is not permitted to have default 149/// arguments. This routine should be invoked for every declarator 150/// that is not a function declaration or definition. 151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 152 // C++ [dcl.fct.default]p3 153 // A default argument expression shall be specified only in the 154 // parameter-declaration-clause of a function declaration or in a 155 // template-parameter (14.1). It shall not be specified for a 156 // parameter pack. If it is specified in a 157 // parameter-declaration-clause, it shall not occur within a 158 // declarator or abstract-declarator of a parameter-declaration. 159 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 160 DeclaratorChunk &chunk = D.getTypeObject(i); 161 if (chunk.Kind == DeclaratorChunk::Function) { 162 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 163 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 164 if (Param->getDefaultArg()) { 165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc, 166 Param->getDefaultArg()->getSourceRange()); 167 Param->setDefaultArg(0); 168 } 169 } 170 } 171 } 172} 173 174// MergeCXXFunctionDecl - Merge two declarations of the same C++ 175// function, once we already know that they have the same 176// type. Subroutine of MergeFunctionDecl. 177FunctionDecl * 178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 179 // C++ [dcl.fct.default]p4: 180 // 181 // For non-template functions, default arguments can be added in 182 // later declarations of a function in the same 183 // scope. Declarations in different scopes have completely 184 // distinct sets of default arguments. That is, declarations in 185 // inner scopes do not acquire default arguments from 186 // declarations in outer scopes, and vice versa. In a given 187 // function declaration, all parameters subsequent to a 188 // parameter with a default argument shall have default 189 // arguments supplied in this or previous declarations. A 190 // default argument shall not be redefined by a later 191 // declaration (not even to the same value). 192 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 193 ParmVarDecl *OldParam = Old->getParamDecl(p); 194 ParmVarDecl *NewParam = New->getParamDecl(p); 195 196 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 197 Diag(NewParam->getLocation(), 198 diag::err_param_default_argument_redefinition, 199 NewParam->getDefaultArg()->getSourceRange()); 200 Diag(OldParam->getLocation(), diag::err_previous_definition); 201 } else if (OldParam->getDefaultArg()) { 202 // Merge the old default argument into the new parameter 203 NewParam->setDefaultArg(OldParam->getDefaultArg()); 204 } 205 } 206 207 return New; 208} 209 210/// CheckCXXDefaultArguments - Verify that the default arguments for a 211/// function declaration are well-formed according to C++ 212/// [dcl.fct.default]. 213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 214 unsigned NumParams = FD->getNumParams(); 215 unsigned p; 216 217 // Find first parameter with a default argument 218 for (p = 0; p < NumParams; ++p) { 219 ParmVarDecl *Param = FD->getParamDecl(p); 220 if (Param->getDefaultArg()) 221 break; 222 } 223 224 // C++ [dcl.fct.default]p4: 225 // In a given function declaration, all parameters 226 // subsequent to a parameter with a default argument shall 227 // have default arguments supplied in this or previous 228 // declarations. A default argument shall not be redefined 229 // by a later declaration (not even to the same value). 230 unsigned LastMissingDefaultArg = 0; 231 for(; p < NumParams; ++p) { 232 ParmVarDecl *Param = FD->getParamDecl(p); 233 if (!Param->getDefaultArg()) { 234 if (Param->getIdentifier()) 235 Diag(Param->getLocation(), 236 diag::err_param_default_argument_missing_name, 237 Param->getIdentifier()->getName()); 238 else 239 Diag(Param->getLocation(), 240 diag::err_param_default_argument_missing); 241 242 LastMissingDefaultArg = p; 243 } 244 } 245 246 if (LastMissingDefaultArg > 0) { 247 // Some default arguments were missing. Clear out all of the 248 // default arguments up to (and including) the last missing 249 // default argument, so that we leave the function parameters 250 // in a semantically valid state. 251 for (p = 0; p <= LastMissingDefaultArg; ++p) { 252 ParmVarDecl *Param = FD->getParamDecl(p); 253 if (Param->getDefaultArg()) { 254 delete Param->getDefaultArg(); 255 Param->setDefaultArg(0); 256 } 257 } 258 } 259} 260 261/// isCurrentClassName - Determine whether the identifier II is the 262/// name of the class type currently being defined. In the case of 263/// nested classes, this will only return true if II is the name of 264/// the innermost class. 265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) { 266 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext)) 267 return &II == CurDecl->getIdentifier(); 268 else 269 return false; 270} 271 272/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 273/// one entry in the base class list of a class specifier, for 274/// example: 275/// class foo : public bar, virtual private baz { 276/// 'public bar' and 'virtual private baz' are each base-specifiers. 277Sema::BaseResult 278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 279 bool Virtual, AccessSpecifier Access, 280 TypeTy *basetype, SourceLocation BaseLoc) { 281 RecordDecl *Decl = (RecordDecl*)classdecl; 282 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 283 284 // Base specifiers must be record types. 285 if (!BaseType->isRecordType()) { 286 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 287 return true; 288 } 289 290 // C++ [class.union]p1: 291 // A union shall not be used as a base class. 292 if (BaseType->isUnionType()) { 293 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 294 return true; 295 } 296 297 // C++ [class.union]p1: 298 // A union shall not have base classes. 299 if (Decl->isUnion()) { 300 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 301 SpecifierRange); 302 return true; 303 } 304 305 // C++ [class.derived]p2: 306 // The class-name in a base-specifier shall not be an incompletely 307 // defined class. 308 if (BaseType->isIncompleteType()) { 309 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 310 return true; 311 } 312 313 // If the base class is polymorphic, the new one is, too. 314 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl(); 315 assert(BaseDecl && "Record type has no declaration"); 316 BaseDecl = BaseDecl->getDefinition(Context); 317 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 318 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) { 319 cast<CXXRecordDecl>(Decl)->setPolymorphic(true); 320 } 321 322 // Create the base specifier. 323 return new CXXBaseSpecifier(SpecifierRange, Virtual, 324 BaseType->isClassType(), Access, BaseType); 325} 326 327/// ActOnBaseSpecifiers - Attach the given base specifiers to the 328/// class, after checking whether there are any duplicate base 329/// classes. 330void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 331 unsigned NumBases) { 332 if (NumBases == 0) 333 return; 334 335 // Used to keep track of which base types we have already seen, so 336 // that we can properly diagnose redundant direct base types. Note 337 // that the key is always the unqualified canonical type of the base 338 // class. 339 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 340 341 // Copy non-redundant base specifiers into permanent storage. 342 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 343 unsigned NumGoodBases = 0; 344 for (unsigned idx = 0; idx < NumBases; ++idx) { 345 QualType NewBaseType 346 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 347 NewBaseType = NewBaseType.getUnqualifiedType(); 348 349 if (KnownBaseTypes[NewBaseType]) { 350 // C++ [class.mi]p3: 351 // A class shall not be specified as a direct base class of a 352 // derived class more than once. 353 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 354 diag::err_duplicate_base_class, 355 KnownBaseTypes[NewBaseType]->getType().getAsString(), 356 BaseSpecs[idx]->getSourceRange()); 357 358 // Delete the duplicate base class specifier; we're going to 359 // overwrite its pointer later. 360 delete BaseSpecs[idx]; 361 } else { 362 // Okay, add this new base class. 363 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 364 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 365 } 366 } 367 368 // Attach the remaining base class specifiers to the derived class. 369 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 370 Decl->setBases(BaseSpecs, NumGoodBases); 371 372 // Delete the remaining (good) base class specifiers, since their 373 // data has been copied into the CXXRecordDecl. 374 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 375 delete BaseSpecs[idx]; 376} 377 378//===----------------------------------------------------------------------===// 379// C++ class member Handling 380//===----------------------------------------------------------------------===// 381 382/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 383/// definition, when on C++. 384void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 385 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 386 PushDeclContext(Dcl); 387 FieldCollector->StartClass(); 388 389 if (Dcl->getIdentifier()) { 390 // C++ [class]p2: 391 // [...] The class-name is also inserted into the scope of the 392 // class itself; this is known as the injected-class-name. For 393 // purposes of access checking, the injected-class-name is treated 394 // as if it were a public member name. 395 // FIXME: this should probably have its own kind of type node. 396 TypedefDecl *InjectedClassName 397 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(), 398 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0); 399 PushOnScopeChains(InjectedClassName, S); 400 } 401} 402 403/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 404/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 405/// bitfield width if there is one and 'InitExpr' specifies the initializer if 406/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 407/// declarators on it. 408/// 409/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 410/// an instance field is declared, a new CXXFieldDecl is created but the method 411/// does *not* return it; it returns LastInGroup instead. The other C++ members 412/// (which are all ScopedDecls) are returned after appending them to 413/// LastInGroup. 414Sema::DeclTy * 415Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 416 ExprTy *BW, ExprTy *InitExpr, 417 DeclTy *LastInGroup) { 418 const DeclSpec &DS = D.getDeclSpec(); 419 IdentifierInfo *II = D.getIdentifier(); 420 Expr *BitWidth = static_cast<Expr*>(BW); 421 Expr *Init = static_cast<Expr*>(InitExpr); 422 SourceLocation Loc = D.getIdentifierLoc(); 423 424 // C++ 9.2p6: A member shall not be declared to have automatic storage 425 // duration (auto, register) or with the extern storage-class-specifier. 426 switch (DS.getStorageClassSpec()) { 427 case DeclSpec::SCS_unspecified: 428 case DeclSpec::SCS_typedef: 429 case DeclSpec::SCS_static: 430 // FALL THROUGH. 431 break; 432 default: 433 if (DS.getStorageClassSpecLoc().isValid()) 434 Diag(DS.getStorageClassSpecLoc(), 435 diag::err_storageclass_invalid_for_member); 436 else 437 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 438 D.getMutableDeclSpec().ClearStorageClassSpecs(); 439 } 440 441 bool isFunc = D.isFunctionDeclarator(); 442 if (!isFunc && 443 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 444 D.getNumTypeObjects() == 0) { 445 // Check also for this case: 446 // 447 // typedef int f(); 448 // f a; 449 // 450 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 451 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 452 } 453 454 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 455 !isFunc); 456 457 Decl *Member; 458 bool InvalidDecl = false; 459 460 if (isInstField) 461 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 462 else 463 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 464 465 if (!Member) return LastInGroup; 466 467 assert((II || isInstField) && "No identifier for non-field ?"); 468 469 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 470 // specific methods. Use a wrapper class that can be used with all C++ class 471 // member decls. 472 CXXClassMemberWrapper(Member).setAccess(AS); 473 474 // C++ [dcl.init.aggr]p1: 475 // An aggregate is an array or a class (clause 9) with [...] no 476 // private or protected non-static data members (clause 11). 477 if (isInstField && (AS == AS_private || AS == AS_protected)) 478 cast<CXXRecordDecl>(CurContext)->setAggregate(false); 479 480 if (DS.isVirtualSpecified()) { 481 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) { 482 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function); 483 InvalidDecl = true; 484 } else { 485 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext); 486 CurClass->setAggregate(false); 487 CurClass->setPolymorphic(true); 488 } 489 } 490 491 if (BitWidth) { 492 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 493 // constant-expression be a value equal to zero. 494 // FIXME: Check this. 495 496 if (D.isFunctionDeclarator()) { 497 // FIXME: Emit diagnostic about only constructors taking base initializers 498 // or something similar, when constructor support is in place. 499 Diag(Loc, diag::err_not_bitfield_type, 500 II->getName(), BitWidth->getSourceRange()); 501 InvalidDecl = true; 502 503 } else if (isInstField) { 504 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 505 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 506 Diag(Loc, diag::err_not_integral_type_bitfield, 507 II->getName(), BitWidth->getSourceRange()); 508 InvalidDecl = true; 509 } 510 511 } else if (isa<FunctionDecl>(Member)) { 512 // A function typedef ("typedef int f(); f a;"). 513 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 514 Diag(Loc, diag::err_not_integral_type_bitfield, 515 II->getName(), BitWidth->getSourceRange()); 516 InvalidDecl = true; 517 518 } else if (isa<TypedefDecl>(Member)) { 519 // "cannot declare 'A' to be a bit-field type" 520 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 521 BitWidth->getSourceRange()); 522 InvalidDecl = true; 523 524 } else { 525 assert(isa<CXXClassVarDecl>(Member) && 526 "Didn't we cover all member kinds?"); 527 // C++ 9.6p3: A bit-field shall not be a static member. 528 // "static member 'A' cannot be a bit-field" 529 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 530 BitWidth->getSourceRange()); 531 InvalidDecl = true; 532 } 533 } 534 535 if (Init) { 536 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 537 // if it declares a static member of const integral or const enumeration 538 // type. 539 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 540 // ...static member of... 541 CVD->setInit(Init); 542 // ...const integral or const enumeration type. 543 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 544 CVD->getType()->isIntegralType()) { 545 // constant-initializer 546 if (CheckForConstantInitializer(Init, CVD->getType())) 547 InvalidDecl = true; 548 549 } else { 550 // not const integral. 551 Diag(Loc, diag::err_member_initialization, 552 II->getName(), Init->getSourceRange()); 553 InvalidDecl = true; 554 } 555 556 } else { 557 // not static member. 558 Diag(Loc, diag::err_member_initialization, 559 II->getName(), Init->getSourceRange()); 560 InvalidDecl = true; 561 } 562 } 563 564 if (InvalidDecl) 565 Member->setInvalidDecl(); 566 567 if (isInstField) { 568 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 569 return LastInGroup; 570 } 571 return Member; 572} 573 574/// ActOnMemInitializer - Handle a C++ member initializer. 575Sema::MemInitResult 576Sema::ActOnMemInitializer(DeclTy *ConstructorD, 577 Scope *S, 578 IdentifierInfo *MemberOrBase, 579 SourceLocation IdLoc, 580 SourceLocation LParenLoc, 581 ExprTy **Args, unsigned NumArgs, 582 SourceLocation *CommaLocs, 583 SourceLocation RParenLoc) { 584 CXXConstructorDecl *Constructor 585 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 586 if (!Constructor) { 587 // The user wrote a constructor initializer on a function that is 588 // not a C++ constructor. Ignore the error for now, because we may 589 // have more member initializers coming; we'll diagnose it just 590 // once in ActOnMemInitializers. 591 return true; 592 } 593 594 CXXRecordDecl *ClassDecl = Constructor->getParent(); 595 596 // C++ [class.base.init]p2: 597 // Names in a mem-initializer-id are looked up in the scope of the 598 // constructor’s class and, if not found in that scope, are looked 599 // up in the scope containing the constructor’s 600 // definition. [Note: if the constructor’s class contains a member 601 // with the same name as a direct or virtual base class of the 602 // class, a mem-initializer-id naming the member or base class and 603 // composed of a single identifier refers to the class member. A 604 // mem-initializer-id for the hidden base class may be specified 605 // using a qualified name. ] 606 // Look for a member, first. 607 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase); 608 609 // FIXME: Handle members of an anonymous union. 610 611 if (Member) { 612 // FIXME: Perform direct initialization of the member. 613 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 614 } 615 616 // It didn't name a member, so see if it names a class. 617 TypeTy *BaseTy = isTypeName(*MemberOrBase, S); 618 if (!BaseTy) 619 return Diag(IdLoc, diag::err_mem_init_not_member_or_class, 620 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 621 622 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy); 623 if (!BaseType->isRecordType()) 624 return Diag(IdLoc, diag::err_base_init_does_not_name_class, 625 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc)); 626 627 // C++ [class.base.init]p2: 628 // [...] Unless the mem-initializer-id names a nonstatic data 629 // member of the constructor’s class or a direct or virtual base 630 // of that class, the mem-initializer is ill-formed. A 631 // mem-initializer-list can initialize a base class using any 632 // name that denotes that base class type. 633 634 // First, check for a direct base class. 635 const CXXBaseSpecifier *DirectBaseSpec = 0; 636 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 637 Base != ClassDecl->bases_end(); ++Base) { 638 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 639 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 640 // We found a direct base of this type. That's what we're 641 // initializing. 642 DirectBaseSpec = &*Base; 643 break; 644 } 645 } 646 647 // Check for a virtual base class. 648 // FIXME: We might be able to short-circuit this if we know in 649 // advance that there are no virtual bases. 650 const CXXBaseSpecifier *VirtualBaseSpec = 0; 651 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 652 // We haven't found a base yet; search the class hierarchy for a 653 // virtual base class. 654 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 655 /*DetectVirtual=*/false); 656 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 657 for (BasePaths::paths_iterator Path = Paths.begin(); 658 Path != Paths.end(); ++Path) { 659 if (Path->back().Base->isVirtual()) { 660 VirtualBaseSpec = Path->back().Base; 661 break; 662 } 663 } 664 } 665 } 666 667 // C++ [base.class.init]p2: 668 // If a mem-initializer-id is ambiguous because it designates both 669 // a direct non-virtual base class and an inherited virtual base 670 // class, the mem-initializer is ill-formed. 671 if (DirectBaseSpec && VirtualBaseSpec) 672 return Diag(IdLoc, diag::err_base_init_direct_and_virtual, 673 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 674 675 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 676} 677 678 679void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 680 DeclTy *TagDecl, 681 SourceLocation LBrac, 682 SourceLocation RBrac) { 683 ActOnFields(S, RLoc, TagDecl, 684 (DeclTy**)FieldCollector->getCurFields(), 685 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 686} 687 688/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 689/// special functions, such as the default constructor, copy 690/// constructor, or destructor, to the given C++ class (C++ 691/// [special]p1). This routine can only be executed just before the 692/// definition of the class is complete. 693void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 694 if (!ClassDecl->hasUserDeclaredConstructor()) { 695 // C++ [class.ctor]p5: 696 // A default constructor for a class X is a constructor of class X 697 // that can be called without an argument. If there is no 698 // user-declared constructor for class X, a default constructor is 699 // implicitly declared. An implicitly-declared default constructor 700 // is an inline public member of its class. 701 CXXConstructorDecl *DefaultCon = 702 CXXConstructorDecl::Create(Context, ClassDecl, 703 ClassDecl->getLocation(), 704 ClassDecl->getIdentifier(), 705 Context.getFunctionType(Context.VoidTy, 706 0, 0, false, 0), 707 /*isExplicit=*/false, 708 /*isInline=*/true, 709 /*isImplicitlyDeclared=*/true); 710 DefaultCon->setAccess(AS_public); 711 ClassDecl->addConstructor(Context, DefaultCon); 712 } 713 714 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 715 // C++ [class.copy]p4: 716 // If the class definition does not explicitly declare a copy 717 // constructor, one is declared implicitly. 718 719 // C++ [class.copy]p5: 720 // The implicitly-declared copy constructor for a class X will 721 // have the form 722 // 723 // X::X(const X&) 724 // 725 // if 726 bool HasConstCopyConstructor = true; 727 728 // -- each direct or virtual base class B of X has a copy 729 // constructor whose first parameter is of type const B& or 730 // const volatile B&, and 731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 732 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 733 const CXXRecordDecl *BaseClassDecl 734 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 735 HasConstCopyConstructor 736 = BaseClassDecl->hasConstCopyConstructor(Context); 737 } 738 739 // -- for all the nonstatic data members of X that are of a 740 // class type M (or array thereof), each such class type 741 // has a copy constructor whose first parameter is of type 742 // const M& or const volatile M&. 743 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 744 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 745 QualType FieldType = (*Field)->getType(); 746 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 747 FieldType = Array->getElementType(); 748 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 749 const CXXRecordDecl *FieldClassDecl 750 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 751 HasConstCopyConstructor 752 = FieldClassDecl->hasConstCopyConstructor(Context); 753 } 754 } 755 756 // Otherwise, the implicitly declared copy constructor will have 757 // the form 758 // 759 // X::X(X&) 760 QualType ArgType = Context.getTypeDeclType(ClassDecl); 761 if (HasConstCopyConstructor) 762 ArgType = ArgType.withConst(); 763 ArgType = Context.getReferenceType(ArgType); 764 765 // An implicitly-declared copy constructor is an inline public 766 // member of its class. 767 CXXConstructorDecl *CopyConstructor 768 = CXXConstructorDecl::Create(Context, ClassDecl, 769 ClassDecl->getLocation(), 770 ClassDecl->getIdentifier(), 771 Context.getFunctionType(Context.VoidTy, 772 &ArgType, 1, 773 false, 0), 774 /*isExplicit=*/false, 775 /*isInline=*/true, 776 /*isImplicitlyDeclared=*/true); 777 CopyConstructor->setAccess(AS_public); 778 779 // Add the parameter to the constructor. 780 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 781 ClassDecl->getLocation(), 782 /*IdentifierInfo=*/0, 783 ArgType, VarDecl::None, 0, 0); 784 CopyConstructor->setParams(&FromParam, 1); 785 786 ClassDecl->addConstructor(Context, CopyConstructor); 787 } 788 789 if (!ClassDecl->getDestructor()) { 790 // C++ [class.dtor]p2: 791 // If a class has no user-declared destructor, a destructor is 792 // declared implicitly. An implicitly-declared destructor is an 793 // inline public member of its class. 794 std::string DestructorName = "~"; 795 DestructorName += ClassDecl->getName(); 796 CXXDestructorDecl *Destructor 797 = CXXDestructorDecl::Create(Context, ClassDecl, 798 ClassDecl->getLocation(), 799 &PP.getIdentifierTable().get(DestructorName), 800 Context.getFunctionType(Context.VoidTy, 801 0, 0, false, 0), 802 /*isInline=*/true, 803 /*isImplicitlyDeclared=*/true); 804 Destructor->setAccess(AS_public); 805 ClassDecl->setDestructor(Destructor); 806 } 807 808 // FIXME: Implicit copy assignment operator 809} 810 811void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 812 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 813 FieldCollector->FinishClass(); 814 AddImplicitlyDeclaredMembersToClass(Rec); 815 PopDeclContext(); 816 817 // Everything, including inline method definitions, have been parsed. 818 // Let the consumer know of the new TagDecl definition. 819 Consumer.HandleTagDeclDefinition(Rec); 820} 821 822/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 823/// the well-formednes of the constructor declarator @p D with type @p 824/// R. If there are any errors in the declarator, this routine will 825/// emit diagnostics and return true. Otherwise, it will return 826/// false. Either way, the type @p R will be updated to reflect a 827/// well-formed type for the constructor. 828bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R, 829 FunctionDecl::StorageClass& SC) { 830 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 831 bool isInvalid = false; 832 833 // C++ [class.ctor]p3: 834 // A constructor shall not be virtual (10.3) or static (9.4). A 835 // constructor can be invoked for a const, volatile or const 836 // volatile object. A constructor shall not be declared const, 837 // volatile, or const volatile (9.3.2). 838 if (isVirtual) { 839 Diag(D.getIdentifierLoc(), 840 diag::err_constructor_cannot_be, 841 "virtual", 842 SourceRange(D.getDeclSpec().getVirtualSpecLoc()), 843 SourceRange(D.getIdentifierLoc())); 844 isInvalid = true; 845 } 846 if (SC == FunctionDecl::Static) { 847 Diag(D.getIdentifierLoc(), 848 diag::err_constructor_cannot_be, 849 "static", 850 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()), 851 SourceRange(D.getIdentifierLoc())); 852 isInvalid = true; 853 SC = FunctionDecl::None; 854 } 855 if (D.getDeclSpec().hasTypeSpecifier()) { 856 // Constructors don't have return types, but the parser will 857 // happily parse something like: 858 // 859 // class X { 860 // float X(float); 861 // }; 862 // 863 // The return type will be eliminated later. 864 Diag(D.getIdentifierLoc(), 865 diag::err_constructor_return_type, 866 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()), 867 SourceRange(D.getIdentifierLoc())); 868 } 869 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 870 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 871 if (FTI.TypeQuals & QualType::Const) 872 Diag(D.getIdentifierLoc(), 873 diag::err_invalid_qualified_constructor, 874 "const", 875 SourceRange(D.getIdentifierLoc())); 876 if (FTI.TypeQuals & QualType::Volatile) 877 Diag(D.getIdentifierLoc(), 878 diag::err_invalid_qualified_constructor, 879 "volatile", 880 SourceRange(D.getIdentifierLoc())); 881 if (FTI.TypeQuals & QualType::Restrict) 882 Diag(D.getIdentifierLoc(), 883 diag::err_invalid_qualified_constructor, 884 "restrict", 885 SourceRange(D.getIdentifierLoc())); 886 } 887 888 // Rebuild the function type "R" without any type qualifiers (in 889 // case any of the errors above fired) and with "void" as the 890 // return type, since constructors don't have return types. We 891 // *always* have to do this, because GetTypeForDeclarator will 892 // put in a result type of "int" when none was specified. 893 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto(); 894 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 895 Proto->getNumArgs(), 896 Proto->isVariadic(), 897 0); 898 899 return isInvalid; 900} 901 902/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 903/// the well-formednes of the destructor declarator @p D with type @p 904/// R. If there are any errors in the declarator, this routine will 905/// emit diagnostics and return true. Otherwise, it will return 906/// false. Either way, the type @p R will be updated to reflect a 907/// well-formed type for the destructor. 908bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R, 909 FunctionDecl::StorageClass& SC) { 910 bool isInvalid = false; 911 912 // C++ [class.dtor]p1: 913 // [...] A typedef-name that names a class is a class-name 914 // (7.1.3); however, a typedef-name that names a class shall not 915 // be used as the identifier in the declarator for a destructor 916 // declaration. 917 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType(); 918 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) { 919 if (TypedefD->getIdentifier() != 920 cast<CXXRecordDecl>(CurContext)->getIdentifier()) { 921 // FIXME: This would be easier if we could just look at whether 922 // we found the injected-class-name. 923 Diag(D.getIdentifierLoc(), 924 diag::err_destructor_typedef_name, 925 TypedefD->getName()); 926 isInvalid = true; 927 } 928 } 929 930 // C++ [class.dtor]p2: 931 // A destructor is used to destroy objects of its class type. A 932 // destructor takes no parameters, and no return type can be 933 // specified for it (not even void). The address of a destructor 934 // shall not be taken. A destructor shall not be static. A 935 // destructor can be invoked for a const, volatile or const 936 // volatile object. A destructor shall not be declared const, 937 // volatile or const volatile (9.3.2). 938 if (SC == FunctionDecl::Static) { 939 Diag(D.getIdentifierLoc(), 940 diag::err_destructor_cannot_be, 941 "static", 942 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()), 943 SourceRange(D.getIdentifierLoc())); 944 isInvalid = true; 945 SC = FunctionDecl::None; 946 } 947 if (D.getDeclSpec().hasTypeSpecifier()) { 948 // Destructors don't have return types, but the parser will 949 // happily parse something like: 950 // 951 // class X { 952 // float ~X(); 953 // }; 954 // 955 // The return type will be eliminated later. 956 Diag(D.getIdentifierLoc(), 957 diag::err_destructor_return_type, 958 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()), 959 SourceRange(D.getIdentifierLoc())); 960 } 961 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 963 if (FTI.TypeQuals & QualType::Const) 964 Diag(D.getIdentifierLoc(), 965 diag::err_invalid_qualified_destructor, 966 "const", 967 SourceRange(D.getIdentifierLoc())); 968 if (FTI.TypeQuals & QualType::Volatile) 969 Diag(D.getIdentifierLoc(), 970 diag::err_invalid_qualified_destructor, 971 "volatile", 972 SourceRange(D.getIdentifierLoc())); 973 if (FTI.TypeQuals & QualType::Restrict) 974 Diag(D.getIdentifierLoc(), 975 diag::err_invalid_qualified_destructor, 976 "restrict", 977 SourceRange(D.getIdentifierLoc())); 978 } 979 980 // Make sure we don't have any parameters. 981 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 982 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 983 984 // Delete the parameters. 985 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 986 if (FTI.NumArgs) { 987 delete [] FTI.ArgInfo; 988 FTI.NumArgs = 0; 989 FTI.ArgInfo = 0; 990 } 991 } 992 993 // Make sure the destructor isn't variadic. 994 if (R->getAsFunctionTypeProto()->isVariadic()) 995 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 996 997 // Rebuild the function type "R" without any type qualifiers or 998 // parameters (in case any of the errors above fired) and with 999 // "void" as the return type, since destructors don't have return 1000 // types. We *always* have to do this, because GetTypeForDeclarator 1001 // will put in a result type of "int" when none was specified. 1002 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1003 1004 return isInvalid; 1005} 1006 1007/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 1008/// the declaration of the given C++ constructor ConDecl that was 1009/// built from declarator D. This routine is responsible for checking 1010/// that the newly-created constructor declaration is well-formed and 1011/// for recording it in the C++ class. Example: 1012/// 1013/// @code 1014/// class X { 1015/// X(); // X::X() will be the ConDecl. 1016/// }; 1017/// @endcode 1018Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 1019 assert(ConDecl && "Expected to receive a constructor declaration"); 1020 1021 // Check default arguments on the constructor 1022 CheckCXXDefaultArguments(ConDecl); 1023 1024 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1025 if (!ClassDecl) { 1026 ConDecl->setInvalidDecl(); 1027 return ConDecl; 1028 } 1029 1030 // Make sure this constructor is an overload of the existing 1031 // constructors. 1032 OverloadedFunctionDecl::function_iterator MatchedDecl; 1033 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) { 1034 Diag(ConDecl->getLocation(), 1035 diag::err_constructor_redeclared, 1036 SourceRange(ConDecl->getLocation())); 1037 Diag((*MatchedDecl)->getLocation(), 1038 diag::err_previous_declaration, 1039 SourceRange((*MatchedDecl)->getLocation())); 1040 ConDecl->setInvalidDecl(); 1041 return ConDecl; 1042 } 1043 1044 1045 // C++ [class.copy]p3: 1046 // A declaration of a constructor for a class X is ill-formed if 1047 // its first parameter is of type (optionally cv-qualified) X and 1048 // either there are no other parameters or else all other 1049 // parameters have default arguments. 1050 if ((ConDecl->getNumParams() == 1) || 1051 (ConDecl->getNumParams() > 1 && 1052 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) { 1053 QualType ParamType = ConDecl->getParamDecl(0)->getType(); 1054 QualType ClassTy = Context.getTagDeclType( 1055 const_cast<CXXRecordDecl*>(ConDecl->getParent())); 1056 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1057 Diag(ConDecl->getLocation(), 1058 diag::err_constructor_byvalue_arg, 1059 SourceRange(ConDecl->getParamDecl(0)->getLocation())); 1060 ConDecl->setInvalidDecl(); 1061 return ConDecl; 1062 } 1063 } 1064 1065 // Add this constructor to the set of constructors of the current 1066 // class. 1067 ClassDecl->addConstructor(Context, ConDecl); 1068 return (DeclTy *)ConDecl; 1069} 1070 1071/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete 1072/// the declaration of the given C++ @p Destructor. This routine is 1073/// responsible for recording the destructor in the C++ class, if 1074/// possible. 1075Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) { 1076 assert(Destructor && "Expected to receive a destructor declaration"); 1077 1078 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext); 1079 1080 // Make sure we aren't redeclaring the destructor. 1081 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) { 1082 Diag(Destructor->getLocation(), diag::err_destructor_redeclared); 1083 Diag(PrevDestructor->getLocation(), 1084 PrevDestructor->isThisDeclarationADefinition()? 1085 diag::err_previous_definition 1086 : diag::err_previous_declaration); 1087 Destructor->setInvalidDecl(); 1088 return Destructor; 1089 } 1090 1091 ClassDecl->setDestructor(Destructor); 1092 return (DeclTy *)Destructor; 1093} 1094 1095//===----------------------------------------------------------------------===// 1096// Namespace Handling 1097//===----------------------------------------------------------------------===// 1098 1099/// ActOnStartNamespaceDef - This is called at the start of a namespace 1100/// definition. 1101Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1102 SourceLocation IdentLoc, 1103 IdentifierInfo *II, 1104 SourceLocation LBrace) { 1105 NamespaceDecl *Namespc = 1106 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1107 Namespc->setLBracLoc(LBrace); 1108 1109 Scope *DeclRegionScope = NamespcScope->getParent(); 1110 1111 if (II) { 1112 // C++ [namespace.def]p2: 1113 // The identifier in an original-namespace-definition shall not have been 1114 // previously defined in the declarative region in which the 1115 // original-namespace-definition appears. The identifier in an 1116 // original-namespace-definition is the name of the namespace. Subsequently 1117 // in that declarative region, it is treated as an original-namespace-name. 1118 1119 Decl *PrevDecl = 1120 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 1121 /*enableLazyBuiltinCreation=*/false); 1122 1123 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 1124 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 1125 // This is an extended namespace definition. 1126 // Attach this namespace decl to the chain of extended namespace 1127 // definitions. 1128 NamespaceDecl *NextNS = OrigNS; 1129 while (NextNS->getNextNamespace()) 1130 NextNS = NextNS->getNextNamespace(); 1131 1132 NextNS->setNextNamespace(Namespc); 1133 Namespc->setOriginalNamespace(OrigNS); 1134 1135 // We won't add this decl to the current scope. We want the namespace 1136 // name to return the original namespace decl during a name lookup. 1137 } else { 1138 // This is an invalid name redefinition. 1139 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 1140 Namespc->getName()); 1141 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1142 Namespc->setInvalidDecl(); 1143 // Continue on to push Namespc as current DeclContext and return it. 1144 } 1145 } else { 1146 // This namespace name is declared for the first time. 1147 PushOnScopeChains(Namespc, DeclRegionScope); 1148 } 1149 } 1150 else { 1151 // FIXME: Handle anonymous namespaces 1152 } 1153 1154 // Although we could have an invalid decl (i.e. the namespace name is a 1155 // redefinition), push it as current DeclContext and try to continue parsing. 1156 PushDeclContext(Namespc->getOriginalNamespace()); 1157 return Namespc; 1158} 1159 1160/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1161/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1162void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 1163 Decl *Dcl = static_cast<Decl *>(D); 1164 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1165 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1166 Namespc->setRBracLoc(RBrace); 1167 PopDeclContext(); 1168} 1169 1170 1171/// AddCXXDirectInitializerToDecl - This action is called immediately after 1172/// ActOnDeclarator, when a C++ direct initializer is present. 1173/// e.g: "int x(1);" 1174void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 1175 ExprTy **ExprTys, unsigned NumExprs, 1176 SourceLocation *CommaLocs, 1177 SourceLocation RParenLoc) { 1178 assert(NumExprs != 0 && ExprTys && "missing expressions"); 1179 Decl *RealDecl = static_cast<Decl *>(Dcl); 1180 1181 // If there is no declaration, there was an error parsing it. Just ignore 1182 // the initializer. 1183 if (RealDecl == 0) { 1184 for (unsigned i = 0; i != NumExprs; ++i) 1185 delete static_cast<Expr *>(ExprTys[i]); 1186 return; 1187 } 1188 1189 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1190 if (!VDecl) { 1191 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 1192 RealDecl->setInvalidDecl(); 1193 return; 1194 } 1195 1196 // We will treat direct-initialization as a copy-initialization: 1197 // int x(1); -as-> int x = 1; 1198 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 1199 // 1200 // Clients that want to distinguish between the two forms, can check for 1201 // direct initializer using VarDecl::hasCXXDirectInitializer(). 1202 // A major benefit is that clients that don't particularly care about which 1203 // exactly form was it (like the CodeGen) can handle both cases without 1204 // special case code. 1205 1206 // C++ 8.5p11: 1207 // The form of initialization (using parentheses or '=') is generally 1208 // insignificant, but does matter when the entity being initialized has a 1209 // class type. 1210 QualType DeclInitType = VDecl->getType(); 1211 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 1212 DeclInitType = Array->getElementType(); 1213 1214 if (VDecl->getType()->isRecordType()) { 1215 CXXConstructorDecl *Constructor 1216 = PerformInitializationByConstructor(DeclInitType, 1217 (Expr **)ExprTys, NumExprs, 1218 VDecl->getLocation(), 1219 SourceRange(VDecl->getLocation(), 1220 RParenLoc), 1221 VDecl->getName(), 1222 IK_Direct); 1223 if (!Constructor) { 1224 RealDecl->setInvalidDecl(); 1225 } 1226 1227 // Let clients know that initialization was done with a direct 1228 // initializer. 1229 VDecl->setCXXDirectInitializer(true); 1230 1231 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 1232 // the initializer. 1233 return; 1234 } 1235 1236 if (NumExprs > 1) { 1237 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg, 1238 SourceRange(VDecl->getLocation(), RParenLoc)); 1239 RealDecl->setInvalidDecl(); 1240 return; 1241 } 1242 1243 // Let clients know that initialization was done with a direct initializer. 1244 VDecl->setCXXDirectInitializer(true); 1245 1246 assert(NumExprs == 1 && "Expected 1 expression"); 1247 // Set the init expression, handles conversions. 1248 AddInitializerToDecl(Dcl, ExprTys[0]); 1249} 1250 1251/// PerformInitializationByConstructor - Perform initialization by 1252/// constructor (C++ [dcl.init]p14), which may occur as part of 1253/// direct-initialization or copy-initialization. We are initializing 1254/// an object of type @p ClassType with the given arguments @p 1255/// Args. @p Loc is the location in the source code where the 1256/// initializer occurs (e.g., a declaration, member initializer, 1257/// functional cast, etc.) while @p Range covers the whole 1258/// initialization. @p InitEntity is the entity being initialized, 1259/// which may by the name of a declaration or a type. @p Kind is the 1260/// kind of initialization we're performing, which affects whether 1261/// explicit constructors will be considered. When successful, returns 1262/// the constructor that will be used to perform the initialization; 1263/// when the initialization fails, emits a diagnostic and returns 1264/// null. 1265CXXConstructorDecl * 1266Sema::PerformInitializationByConstructor(QualType ClassType, 1267 Expr **Args, unsigned NumArgs, 1268 SourceLocation Loc, SourceRange Range, 1269 std::string InitEntity, 1270 InitializationKind Kind) { 1271 const RecordType *ClassRec = ClassType->getAsRecordType(); 1272 assert(ClassRec && "Can only initialize a class type here"); 1273 1274 // C++ [dcl.init]p14: 1275 // 1276 // If the initialization is direct-initialization, or if it is 1277 // copy-initialization where the cv-unqualified version of the 1278 // source type is the same class as, or a derived class of, the 1279 // class of the destination, constructors are considered. The 1280 // applicable constructors are enumerated (13.3.1.3), and the 1281 // best one is chosen through overload resolution (13.3). The 1282 // constructor so selected is called to initialize the object, 1283 // with the initializer expression(s) as its argument(s). If no 1284 // constructor applies, or the overload resolution is ambiguous, 1285 // the initialization is ill-formed. 1286 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1287 OverloadCandidateSet CandidateSet; 1288 1289 // Add constructors to the overload set. 1290 OverloadedFunctionDecl *Constructors 1291 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors()); 1292 for (OverloadedFunctionDecl::function_iterator Con 1293 = Constructors->function_begin(); 1294 Con != Constructors->function_end(); ++Con) { 1295 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1296 if ((Kind == IK_Direct) || 1297 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1298 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1299 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1300 } 1301 1302 OverloadCandidateSet::iterator Best; 1303 switch (BestViableFunction(CandidateSet, Best)) { 1304 case OR_Success: 1305 // We found a constructor. Return it. 1306 return cast<CXXConstructorDecl>(Best->Function); 1307 1308 case OR_No_Viable_Function: 1309 if (CandidateSet.empty()) 1310 Diag(Loc, diag::err_ovl_no_viable_function_in_init, 1311 InitEntity, Range); 1312 else { 1313 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands, 1314 InitEntity, Range); 1315 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1316 } 1317 return 0; 1318 1319 case OR_Ambiguous: 1320 Diag(Loc, diag::err_ovl_ambiguous_init, 1321 InitEntity, Range); 1322 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1323 return 0; 1324 } 1325 1326 return 0; 1327} 1328 1329/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1330/// determine whether they are reference-related, 1331/// reference-compatible, reference-compatible with added 1332/// qualification, or incompatible, for use in C++ initialization by 1333/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1334/// type, and the first type (T1) is the pointee type of the reference 1335/// type being initialized. 1336Sema::ReferenceCompareResult 1337Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1338 bool& DerivedToBase) { 1339 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1340 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1341 1342 T1 = Context.getCanonicalType(T1); 1343 T2 = Context.getCanonicalType(T2); 1344 QualType UnqualT1 = T1.getUnqualifiedType(); 1345 QualType UnqualT2 = T2.getUnqualifiedType(); 1346 1347 // C++ [dcl.init.ref]p4: 1348 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1349 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1350 // T1 is a base class of T2. 1351 if (UnqualT1 == UnqualT2) 1352 DerivedToBase = false; 1353 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1354 DerivedToBase = true; 1355 else 1356 return Ref_Incompatible; 1357 1358 // At this point, we know that T1 and T2 are reference-related (at 1359 // least). 1360 1361 // C++ [dcl.init.ref]p4: 1362 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1363 // reference-related to T2 and cv1 is the same cv-qualification 1364 // as, or greater cv-qualification than, cv2. For purposes of 1365 // overload resolution, cases for which cv1 is greater 1366 // cv-qualification than cv2 are identified as 1367 // reference-compatible with added qualification (see 13.3.3.2). 1368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1369 return Ref_Compatible; 1370 else if (T1.isMoreQualifiedThan(T2)) 1371 return Ref_Compatible_With_Added_Qualification; 1372 else 1373 return Ref_Related; 1374} 1375 1376/// CheckReferenceInit - Check the initialization of a reference 1377/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1378/// the initializer (either a simple initializer or an initializer 1379/// list), and DeclType is the type of the declaration. When ICS is 1380/// non-null, this routine will compute the implicit conversion 1381/// sequence according to C++ [over.ics.ref] and will not produce any 1382/// diagnostics; when ICS is null, it will emit diagnostics when any 1383/// errors are found. Either way, a return value of true indicates 1384/// that there was a failure, a return value of false indicates that 1385/// the reference initialization succeeded. 1386/// 1387/// When @p SuppressUserConversions, user-defined conversions are 1388/// suppressed. 1389bool 1390Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1391 ImplicitConversionSequence *ICS, 1392 bool SuppressUserConversions) { 1393 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1394 1395 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1396 QualType T2 = Init->getType(); 1397 1398 // Compute some basic properties of the types and the initializer. 1399 bool DerivedToBase = false; 1400 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1401 ReferenceCompareResult RefRelationship 1402 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1403 1404 // Most paths end in a failed conversion. 1405 if (ICS) 1406 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1407 1408 // C++ [dcl.init.ref]p5: 1409 // A reference to type “cv1 T1” is initialized by an expression 1410 // of type “cv2 T2” as follows: 1411 1412 // -- If the initializer expression 1413 1414 bool BindsDirectly = false; 1415 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1416 // reference-compatible with “cv2 T2,” or 1417 // 1418 // Note that the bit-field check is skipped if we are just computing 1419 // the implicit conversion sequence (C++ [over.best.ics]p2). 1420 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1421 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1422 BindsDirectly = true; 1423 1424 if (ICS) { 1425 // C++ [over.ics.ref]p1: 1426 // When a parameter of reference type binds directly (8.5.3) 1427 // to an argument expression, the implicit conversion sequence 1428 // is the identity conversion, unless the argument expression 1429 // has a type that is a derived class of the parameter type, 1430 // in which case the implicit conversion sequence is a 1431 // derived-to-base Conversion (13.3.3.1). 1432 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1433 ICS->Standard.First = ICK_Identity; 1434 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1435 ICS->Standard.Third = ICK_Identity; 1436 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1437 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1438 ICS->Standard.ReferenceBinding = true; 1439 ICS->Standard.DirectBinding = true; 1440 1441 // Nothing more to do: the inaccessibility/ambiguity check for 1442 // derived-to-base conversions is suppressed when we're 1443 // computing the implicit conversion sequence (C++ 1444 // [over.best.ics]p2). 1445 return false; 1446 } else { 1447 // Perform the conversion. 1448 // FIXME: Binding to a subobject of the lvalue is going to require 1449 // more AST annotation than this. 1450 ImpCastExprToType(Init, T1); 1451 } 1452 } 1453 1454 // -- has a class type (i.e., T2 is a class type) and can be 1455 // implicitly converted to an lvalue of type “cv3 T3,” 1456 // where “cv1 T1” is reference-compatible with “cv3 T3” 1457 // 92) (this conversion is selected by enumerating the 1458 // applicable conversion functions (13.3.1.6) and choosing 1459 // the best one through overload resolution (13.3)), 1460 // FIXME: Implement this second bullet, once we have conversion 1461 // functions. Also remember C++ [over.ics.ref]p1, second part. 1462 1463 if (BindsDirectly) { 1464 // C++ [dcl.init.ref]p4: 1465 // [...] In all cases where the reference-related or 1466 // reference-compatible relationship of two types is used to 1467 // establish the validity of a reference binding, and T1 is a 1468 // base class of T2, a program that necessitates such a binding 1469 // is ill-formed if T1 is an inaccessible (clause 11) or 1470 // ambiguous (10.2) base class of T2. 1471 // 1472 // Note that we only check this condition when we're allowed to 1473 // complain about errors, because we should not be checking for 1474 // ambiguity (or inaccessibility) unless the reference binding 1475 // actually happens. 1476 if (DerivedToBase) 1477 return CheckDerivedToBaseConversion(T2, T1, 1478 Init->getSourceRange().getBegin(), 1479 Init->getSourceRange()); 1480 else 1481 return false; 1482 } 1483 1484 // -- Otherwise, the reference shall be to a non-volatile const 1485 // type (i.e., cv1 shall be const). 1486 if (T1.getCVRQualifiers() != QualType::Const) { 1487 if (!ICS) 1488 Diag(Init->getSourceRange().getBegin(), 1489 diag::err_not_reference_to_const_init, 1490 T1.getAsString(), 1491 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1492 T2.getAsString(), Init->getSourceRange()); 1493 return true; 1494 } 1495 1496 // -- If the initializer expression is an rvalue, with T2 a 1497 // class type, and “cv1 T1” is reference-compatible with 1498 // “cv2 T2,” the reference is bound in one of the 1499 // following ways (the choice is implementation-defined): 1500 // 1501 // -- The reference is bound to the object represented by 1502 // the rvalue (see 3.10) or to a sub-object within that 1503 // object. 1504 // 1505 // -- A temporary of type “cv1 T2” [sic] is created, and 1506 // a constructor is called to copy the entire rvalue 1507 // object into the temporary. The reference is bound to 1508 // the temporary or to a sub-object within the 1509 // temporary. 1510 // 1511 // 1512 // The constructor that would be used to make the copy 1513 // shall be callable whether or not the copy is actually 1514 // done. 1515 // 1516 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1517 // freedom, so we will always take the first option and never build 1518 // a temporary in this case. FIXME: We will, however, have to check 1519 // for the presence of a copy constructor in C++98/03 mode. 1520 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1521 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1522 if (ICS) { 1523 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1524 ICS->Standard.First = ICK_Identity; 1525 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1526 ICS->Standard.Third = ICK_Identity; 1527 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1528 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1529 ICS->Standard.ReferenceBinding = true; 1530 ICS->Standard.DirectBinding = false; 1531 } else { 1532 // FIXME: Binding to a subobject of the rvalue is going to require 1533 // more AST annotation than this. 1534 ImpCastExprToType(Init, T1); 1535 } 1536 return false; 1537 } 1538 1539 // -- Otherwise, a temporary of type “cv1 T1” is created and 1540 // initialized from the initializer expression using the 1541 // rules for a non-reference copy initialization (8.5). The 1542 // reference is then bound to the temporary. If T1 is 1543 // reference-related to T2, cv1 must be the same 1544 // cv-qualification as, or greater cv-qualification than, 1545 // cv2; otherwise, the program is ill-formed. 1546 if (RefRelationship == Ref_Related) { 1547 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1548 // we would be reference-compatible or reference-compatible with 1549 // added qualification. But that wasn't the case, so the reference 1550 // initialization fails. 1551 if (!ICS) 1552 Diag(Init->getSourceRange().getBegin(), 1553 diag::err_reference_init_drops_quals, 1554 T1.getAsString(), 1555 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1556 T2.getAsString(), Init->getSourceRange()); 1557 return true; 1558 } 1559 1560 // Actually try to convert the initializer to T1. 1561 if (ICS) { 1562 /// C++ [over.ics.ref]p2: 1563 /// 1564 /// When a parameter of reference type is not bound directly to 1565 /// an argument expression, the conversion sequence is the one 1566 /// required to convert the argument expression to the 1567 /// underlying type of the reference according to 1568 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1569 /// to copy-initializing a temporary of the underlying type with 1570 /// the argument expression. Any difference in top-level 1571 /// cv-qualification is subsumed by the initialization itself 1572 /// and does not constitute a conversion. 1573 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1574 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1575 } else { 1576 return PerformImplicitConversion(Init, T1); 1577 } 1578} 1579 1580/// CheckOverloadedOperatorDeclaration - Check whether the declaration 1581/// of this overloaded operator is well-formed. If so, returns false; 1582/// otherwise, emits appropriate diagnostics and returns true. 1583bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 1584 assert(FnDecl && FnDecl->getOverloadedOperator() != OO_None && 1585 "Expected an overloaded operator declaration"); 1586 1587 bool IsInvalid = false; 1588 1589 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 1590 1591 // C++ [over.oper]p5: 1592 // The allocation and deallocation functions, operator new, 1593 // operator new[], operator delete and operator delete[], are 1594 // described completely in 3.7.3. The attributes and restrictions 1595 // found in the rest of this subclause do not apply to them unless 1596 // explicitly stated in 3.7.3. 1597 // FIXME: Write a separate routine for checking this. For now, just 1598 // allow it. 1599 if (Op == OO_New || Op == OO_Array_New || 1600 Op == OO_Delete || Op == OO_Array_Delete) 1601 return false; 1602 1603 // C++ [over.oper]p6: 1604 // An operator function shall either be a non-static member 1605 // function or be a non-member function and have at least one 1606 // parameter whose type is a class, a reference to a class, an 1607 // enumeration, or a reference to an enumeration. 1608 CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl); 1609 if (MethodDecl) { 1610 if (MethodDecl->isStatic()) { 1611 Diag(FnDecl->getLocation(), 1612 diag::err_operator_overload_static, 1613 FnDecl->getName(), 1614 SourceRange(FnDecl->getLocation())); 1615 IsInvalid = true; 1616 1617 // Pretend this isn't a member function; it'll supress 1618 // additional, unnecessary error messages. 1619 MethodDecl = 0; 1620 } 1621 } else { 1622 bool ClassOrEnumParam = false; 1623 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 1624 Param != FnDecl->param_end(); ++Param) { 1625 QualType ParamType = (*Param)->getType(); 1626 if (const ReferenceType *RefType = ParamType->getAsReferenceType()) 1627 ParamType = RefType->getPointeeType(); 1628 if (ParamType->isRecordType() || ParamType->isEnumeralType()) { 1629 ClassOrEnumParam = true; 1630 break; 1631 } 1632 } 1633 1634 if (!ClassOrEnumParam) { 1635 Diag(FnDecl->getLocation(), 1636 diag::err_operator_overload_needs_class_or_enum, 1637 FnDecl->getName(), 1638 SourceRange(FnDecl->getLocation())); 1639 IsInvalid = true; 1640 } 1641 } 1642 1643 // C++ [over.oper]p8: 1644 // An operator function cannot have default arguments (8.3.6), 1645 // except where explicitly stated below. 1646 // 1647 // Only the function-call operator allows default arguments 1648 // (C++ [over.call]p1). 1649 if (Op != OO_Call) { 1650 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 1651 Param != FnDecl->param_end(); ++Param) { 1652 if (Expr *DefArg = (*Param)->getDefaultArg()) { 1653 Diag((*Param)->getLocation(), 1654 diag::err_operator_overload_default_arg, 1655 DefArg->getSourceRange()); 1656 IsInvalid = true; 1657 } 1658 } 1659 } 1660 1661 bool CanBeUnaryOperator = false; 1662 bool CanBeBinaryOperator = false; 1663 bool MustBeMemberOperator = false; 1664 1665 switch (Op) { 1666 case OO_New: 1667 case OO_Delete: 1668 case OO_Array_New: 1669 case OO_Array_Delete: 1670 assert(false && "Operators new, new[], delete, and delete[] handled above"); 1671 return true; 1672 1673 // Unary-only operators 1674 case OO_Arrow: 1675 MustBeMemberOperator = true; 1676 // Fall through 1677 1678 case OO_Tilde: 1679 case OO_Exclaim: 1680 CanBeUnaryOperator = true; 1681 break; 1682 1683 // Binary-only operators 1684 case OO_Equal: 1685 case OO_Subscript: 1686 MustBeMemberOperator = true; 1687 // Fall through 1688 1689 case OO_Slash: 1690 case OO_Percent: 1691 case OO_Caret: 1692 case OO_Pipe: 1693 case OO_Less: 1694 case OO_Greater: 1695 case OO_PlusEqual: 1696 case OO_MinusEqual: 1697 case OO_StarEqual: 1698 case OO_SlashEqual: 1699 case OO_PercentEqual: 1700 case OO_CaretEqual: 1701 case OO_AmpEqual: 1702 case OO_PipeEqual: 1703 case OO_LessLess: 1704 case OO_GreaterGreater: 1705 case OO_LessLessEqual: 1706 case OO_GreaterGreaterEqual: 1707 case OO_EqualEqual: 1708 case OO_ExclaimEqual: 1709 case OO_LessEqual: 1710 case OO_GreaterEqual: 1711 case OO_AmpAmp: 1712 case OO_PipePipe: 1713 case OO_Comma: 1714 CanBeBinaryOperator = true; 1715 break; 1716 1717 // Unary or binary operators 1718 case OO_Amp: 1719 case OO_Plus: 1720 case OO_Minus: 1721 case OO_Star: 1722 case OO_PlusPlus: 1723 case OO_MinusMinus: 1724 case OO_ArrowStar: 1725 CanBeUnaryOperator = true; 1726 CanBeBinaryOperator = true; 1727 break; 1728 1729 case OO_Call: 1730 MustBeMemberOperator = true; 1731 break; 1732 1733 case OO_None: 1734 case NUM_OVERLOADED_OPERATORS: 1735 assert(false && "Not an overloaded operator!"); 1736 return true; 1737 } 1738 1739 // C++ [over.oper]p8: 1740 // [...] Operator functions cannot have more or fewer parameters 1741 // than the number required for the corresponding operator, as 1742 // described in the rest of this subclause. 1743 unsigned NumParams = FnDecl->getNumParams() + (MethodDecl? 1 : 0); 1744 if (Op != OO_Call && 1745 ((NumParams == 1 && !CanBeUnaryOperator) || 1746 (NumParams == 2 && !CanBeBinaryOperator) || 1747 (NumParams < 1) || (NumParams > 2))) { 1748 // We have the wrong number of parameters. 1749 std::string NumParamsStr = (llvm::APSInt(32) = NumParams).toString(10); 1750 std::string NumParamsPlural; 1751 if (NumParams != 1) 1752 NumParamsPlural = "s"; 1753 1754 diag::kind DK; 1755 1756 if (CanBeUnaryOperator && CanBeBinaryOperator) 1757 DK = diag::err_operator_overload_must_be_unary_or_binary; 1758 else if (CanBeUnaryOperator) 1759 DK = diag::err_operator_overload_must_be_unary; 1760 else if (CanBeBinaryOperator) 1761 DK = diag::err_operator_overload_must_be_binary; 1762 else 1763 assert(false && "All non-call overloaded operators are unary or binary!"); 1764 1765 Diag(FnDecl->getLocation(), DK, 1766 FnDecl->getName(), NumParamsStr, NumParamsPlural, 1767 SourceRange(FnDecl->getLocation())); 1768 IsInvalid = true; 1769 } 1770 1771 // Overloaded operators cannot be variadic. 1772 if (FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) { 1773 Diag(FnDecl->getLocation(), 1774 diag::err_operator_overload_variadic, 1775 SourceRange(FnDecl->getLocation())); 1776 IsInvalid = true; 1777 } 1778 1779 // Some operators must be non-static member functions. 1780 if (MustBeMemberOperator && !MethodDecl) { 1781 Diag(FnDecl->getLocation(), 1782 diag::err_operator_overload_must_be_member, 1783 FnDecl->getName(), 1784 SourceRange(FnDecl->getLocation())); 1785 IsInvalid = true; 1786 } 1787 1788 // C++ [over.inc]p1: 1789 // The user-defined function called operator++ implements the 1790 // prefix and postfix ++ operator. If this function is a member 1791 // function with no parameters, or a non-member function with one 1792 // parameter of class or enumeration type, it defines the prefix 1793 // increment operator ++ for objects of that type. If the function 1794 // is a member function with one parameter (which shall be of type 1795 // int) or a non-member function with two parameters (the second 1796 // of which shall be of type int), it defines the postfix 1797 // increment operator ++ for objects of that type. 1798 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 1799 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 1800 bool ParamIsInt = false; 1801 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 1802 ParamIsInt = BT->getKind() == BuiltinType::Int; 1803 1804 if (!ParamIsInt) { 1805 Diag(LastParam->getLocation(), 1806 diag::err_operator_overload_post_incdec_must_be_int, 1807 MethodDecl? std::string() : std::string("second "), 1808 (Op == OO_PlusPlus)? std::string("increment") 1809 : std::string("decrement"), 1810 Context.getCanonicalType(LastParam->getType()).getAsString(), 1811 SourceRange(FnDecl->getLocation())); 1812 IsInvalid = true; 1813 } 1814 } 1815 1816 return IsInvalid; 1817} 1818