SemaDeclCXX.cpp revision 38f16717fc72b2c9dcde319ae04bccc4b79a94e3
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/Basic/LangOptions.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/Expr.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/AST/Type.h" 22#include "clang/Parse/Scope.h" 23#include "llvm/ADT/OwningPtr.h" 24#include "llvm/Support/Compiler.h" 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 { 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 }; 51 52 /// VisitExpr - Visit all of the children of this expression. 53 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 54 bool IsInvalid = false; 55 for (Stmt::child_iterator first = Node->child_begin(), 56 last = Node->child_end(); 57 first != last; ++first) 58 IsInvalid |= Visit(*first); 59 60 return IsInvalid; 61 } 62 63 /// VisitDeclRefExpr - Visit a reference to a declaration, to 64 /// determine whether this declaration can be used in the default 65 /// argument expression. 66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 67 ValueDecl *Decl = DRE->getDecl(); 68 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 69 // C++ [dcl.fct.default]p9 70 // Default arguments are evaluated each time the function is 71 // called. The order of evaluation of function arguments is 72 // unspecified. Consequently, parameters of a function shall not 73 // be used in default argument expressions, even if they are not 74 // evaluated. Parameters of a function declared before a default 75 // argument expression are in scope and can hide namespace and 76 // class member names. 77 return S->Diag(DRE->getSourceRange().getBegin(), 78 diag::err_param_default_argument_references_param, 79 Param->getName(), DefaultArg->getSourceRange()); 80 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 81 // C++ [dcl.fct.default]p7 82 // Local variables shall not be used in default argument 83 // expressions. 84 if (VDecl->isBlockVarDecl()) 85 return S->Diag(DRE->getSourceRange().getBegin(), 86 diag::err_param_default_argument_references_local, 87 VDecl->getName(), DefaultArg->getSourceRange()); 88 } 89 90 // FIXME: when Clang has support for member functions, "this" 91 // will also need to be diagnosed. 92 93 return false; 94 } 95} 96 97/// ActOnParamDefaultArgument - Check whether the default argument 98/// provided for a function parameter is well-formed. If so, attach it 99/// to the parameter declaration. 100void 101Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 102 ExprTy *defarg) { 103 ParmVarDecl *Param = (ParmVarDecl *)param; 104 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 105 QualType ParamType = Param->getType(); 106 107 // Default arguments are only permitted in C++ 108 if (!getLangOptions().CPlusPlus) { 109 Diag(EqualLoc, diag::err_param_default_argument, 110 DefaultArg->getSourceRange()); 111 return; 112 } 113 114 // C++ [dcl.fct.default]p5 115 // A default argument expression is implicitly converted (clause 116 // 4) to the parameter type. The default argument expression has 117 // the same semantic constraints as the initializer expression in 118 // a declaration of a variable of the parameter type, using the 119 // copy-initialization semantics (8.5). 120 // 121 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics 122 // for C++ (since we want copy-initialization, not copy-assignment), 123 // but we don't have the right semantics implemented yet. Because of 124 // this, our error message is also very poor. 125 QualType DefaultArgType = DefaultArg->getType(); 126 Expr *DefaultArgPtr = DefaultArg.get(); 127 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType, 128 DefaultArgPtr); 129 if (DefaultArgPtr != DefaultArg.get()) { 130 DefaultArg.take(); 131 DefaultArg.reset(DefaultArgPtr); 132 } 133 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(), 134 ParamType, DefaultArgType, DefaultArg.get(), 135 "in default argument")) { 136 return; 137 } 138 139 // Check that the default argument is well-formed 140 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 141 if (DefaultArgChecker.Visit(DefaultArg.get())) 142 return; 143 144 // Okay: add the default argument to the parameter 145 Param->setDefaultArg(DefaultArg.take()); 146} 147 148/// CheckExtraCXXDefaultArguments - Check for any extra default 149/// arguments in the declarator, which is not a function declaration 150/// or definition and therefore is not permitted to have default 151/// arguments. This routine should be invoked for every declarator 152/// that is not a function declaration or definition. 153void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 154 // C++ [dcl.fct.default]p3 155 // A default argument expression shall be specified only in the 156 // parameter-declaration-clause of a function declaration or in a 157 // template-parameter (14.1). It shall not be specified for a 158 // parameter pack. If it is specified in a 159 // parameter-declaration-clause, it shall not occur within a 160 // declarator or abstract-declarator of a parameter-declaration. 161 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 162 DeclaratorChunk &chunk = D.getTypeObject(i); 163 if (chunk.Kind == DeclaratorChunk::Function) { 164 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 165 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 166 if (Param->getDefaultArg()) { 167 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc, 168 Param->getDefaultArg()->getSourceRange()); 169 Param->setDefaultArg(0); 170 } 171 } 172 } 173 } 174} 175 176// MergeCXXFunctionDecl - Merge two declarations of the same C++ 177// function, once we already know that they have the same 178// type. Subroutine of MergeFunctionDecl. 179FunctionDecl * 180Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 181 // C++ [dcl.fct.default]p4: 182 // 183 // For non-template functions, default arguments can be added in 184 // later declarations of a function in the same 185 // scope. Declarations in different scopes have completely 186 // distinct sets of default arguments. That is, declarations in 187 // inner scopes do not acquire default arguments from 188 // declarations in outer scopes, and vice versa. In a given 189 // function declaration, all parameters subsequent to a 190 // parameter with a default argument shall have default 191 // arguments supplied in this or previous declarations. A 192 // default argument shall not be redefined by a later 193 // declaration (not even to the same value). 194 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 195 ParmVarDecl *OldParam = Old->getParamDecl(p); 196 ParmVarDecl *NewParam = New->getParamDecl(p); 197 198 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 199 Diag(NewParam->getLocation(), 200 diag::err_param_default_argument_redefinition, 201 NewParam->getDefaultArg()->getSourceRange()); 202 Diag(OldParam->getLocation(), diag::err_previous_definition); 203 } else if (OldParam->getDefaultArg()) { 204 // Merge the old default argument into the new parameter 205 NewParam->setDefaultArg(OldParam->getDefaultArg()); 206 } 207 } 208 209 return New; 210} 211 212/// CheckCXXDefaultArguments - Verify that the default arguments for a 213/// function declaration are well-formed according to C++ 214/// [dcl.fct.default]. 215void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 216 unsigned NumParams = FD->getNumParams(); 217 unsigned p; 218 219 // Find first parameter with a default argument 220 for (p = 0; p < NumParams; ++p) { 221 ParmVarDecl *Param = FD->getParamDecl(p); 222 if (Param->getDefaultArg()) 223 break; 224 } 225 226 // C++ [dcl.fct.default]p4: 227 // In a given function declaration, all parameters 228 // subsequent to a parameter with a default argument shall 229 // have default arguments supplied in this or previous 230 // declarations. A default argument shall not be redefined 231 // by a later declaration (not even to the same value). 232 unsigned LastMissingDefaultArg = 0; 233 for(; p < NumParams; ++p) { 234 ParmVarDecl *Param = FD->getParamDecl(p); 235 if (!Param->getDefaultArg()) { 236 if (Param->getIdentifier()) 237 Diag(Param->getLocation(), 238 diag::err_param_default_argument_missing_name, 239 Param->getIdentifier()->getName()); 240 else 241 Diag(Param->getLocation(), 242 diag::err_param_default_argument_missing); 243 244 LastMissingDefaultArg = p; 245 } 246 } 247 248 if (LastMissingDefaultArg > 0) { 249 // Some default arguments were missing. Clear out all of the 250 // default arguments up to (and including) the last missing 251 // default argument, so that we leave the function parameters 252 // in a semantically valid state. 253 for (p = 0; p <= LastMissingDefaultArg; ++p) { 254 ParmVarDecl *Param = FD->getParamDecl(p); 255 if (Param->getDefaultArg()) { 256 delete Param->getDefaultArg(); 257 Param->setDefaultArg(0); 258 } 259 } 260 } 261} 262 263/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 264/// one entry in the base class list of a class specifier, for 265/// example: 266/// class foo : public bar, virtual private baz { 267/// 'public bar' and 'virtual private baz' are each base-specifiers. 268void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 269 bool Virtual, AccessSpecifier Access, 270 DeclTy *basetype, SourceLocation BaseLoc) { 271 RecordDecl *Decl = (RecordDecl*)classdecl; 272 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 273 274 // Base specifiers must be record types. 275 if (!BaseType->isRecordType()) { 276 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 277 return; 278 } 279 280 // C++ [class.union]p1: 281 // A union shall not be used as a base class. 282 if (BaseType->isUnionType()) { 283 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 284 return; 285 } 286 287 // C++ [class.union]p1: 288 // A union shall not have base classes. 289 if (Decl->isUnion()) { 290 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 291 SpecifierRange); 292 Decl->setInvalidDecl(); 293 return; 294 } 295 296 // C++ [class.derived]p2: 297 // The class-name in a base-specifier shall not be an incompletely 298 // defined class. 299 if (BaseType->isIncompleteType()) { 300 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 301 return; 302 } 303 304 // FIXME: C++ [class.mi]p3: 305 // A class shall not be specified as a direct base class of a 306 // derived class more than once. 307 308 // FIXME: Attach base class to the record. 309} 310 311//===----------------------------------------------------------------------===// 312// C++ class member Handling 313//===----------------------------------------------------------------------===// 314 315/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 316/// definition, when on C++. 317void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 318 Decl *Dcl = static_cast<Decl *>(D); 319 PushDeclContext(cast<CXXRecordDecl>(Dcl)); 320 FieldCollector->StartClass(); 321} 322 323/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 324/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 325/// bitfield width if there is one and 'InitExpr' specifies the initializer if 326/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 327/// declarators on it. 328/// 329/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 330/// an instance field is declared, a new CXXFieldDecl is created but the method 331/// does *not* return it; it returns LastInGroup instead. The other C++ members 332/// (which are all ScopedDecls) are returned after appending them to 333/// LastInGroup. 334Sema::DeclTy * 335Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 336 ExprTy *BW, ExprTy *InitExpr, 337 DeclTy *LastInGroup) { 338 const DeclSpec &DS = D.getDeclSpec(); 339 IdentifierInfo *II = D.getIdentifier(); 340 Expr *BitWidth = static_cast<Expr*>(BW); 341 Expr *Init = static_cast<Expr*>(InitExpr); 342 SourceLocation Loc = D.getIdentifierLoc(); 343 344 // C++ 9.2p6: A member shall not be declared to have automatic storage 345 // duration (auto, register) or with the extern storage-class-specifier. 346 switch (DS.getStorageClassSpec()) { 347 case DeclSpec::SCS_unspecified: 348 case DeclSpec::SCS_typedef: 349 case DeclSpec::SCS_static: 350 // FALL THROUGH. 351 break; 352 default: 353 if (DS.getStorageClassSpecLoc().isValid()) 354 Diag(DS.getStorageClassSpecLoc(), 355 diag::err_storageclass_invalid_for_member); 356 else 357 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 358 D.getMutableDeclSpec().ClearStorageClassSpecs(); 359 } 360 361 QualType T = GetTypeForDeclarator(D, S); 362 363 // T->isFunctionType() is used instead of D.isFunctionDeclarator() to cover 364 // this case: 365 // 366 // typedef int f(); 367 // f a; 368 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 369 !T->isFunctionType()); 370 371 Decl *Member; 372 bool InvalidDecl = false; 373 374 if (isInstField) 375 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 376 else 377 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 378 379 if (!Member) return LastInGroup; 380 381 assert(II || isInstField && "No identifier for non-field ?"); 382 383 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 384 // specific methods. Use a wrapper class that can be used with all C++ class 385 // member decls. 386 CXXClassMemberWrapper(Member).setAccess(AS); 387 388 if (BitWidth) { 389 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 390 // constant-expression be a value equal to zero. 391 // FIXME: Check this. 392 393 if (D.isFunctionDeclarator()) { 394 // FIXME: Emit diagnostic about only constructors taking base initializers 395 // or something similar, when constructor support is in place. 396 Diag(Loc, diag::err_not_bitfield_type, 397 II->getName(), BitWidth->getSourceRange()); 398 InvalidDecl = true; 399 400 } else if (isInstField || isa<FunctionDecl>(Member)) { 401 // An instance field or a function typedef ("typedef int f(); f a;"). 402 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 403 if (!T->isIntegralType()) { 404 Diag(Loc, diag::err_not_integral_type_bitfield, 405 II->getName(), BitWidth->getSourceRange()); 406 InvalidDecl = true; 407 } 408 409 } else if (isa<TypedefDecl>(Member)) { 410 // "cannot declare 'A' to be a bit-field type" 411 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 412 BitWidth->getSourceRange()); 413 InvalidDecl = true; 414 415 } else { 416 assert(isa<CXXClassVarDecl>(Member) && 417 "Didn't we cover all member kinds?"); 418 // C++ 9.6p3: A bit-field shall not be a static member. 419 // "static member 'A' cannot be a bit-field" 420 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 421 BitWidth->getSourceRange()); 422 InvalidDecl = true; 423 } 424 } 425 426 if (Init) { 427 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 428 // if it declares a static member of const integral or const enumeration 429 // type. 430 if (CXXClassVarDecl *CVD = 431 dyn_cast<CXXClassVarDecl>(Member)) { // ...static member of... 432 CVD->setInit(Init); 433 QualType MemberTy = CVD->getType().getCanonicalType(); 434 // ...const integral or const enumeration type. 435 if (MemberTy.isConstQualified() && MemberTy->isIntegralType()) { 436 if (CheckForConstantInitializer(Init, MemberTy)) // constant-initializer 437 InvalidDecl = true; 438 439 } else { 440 // not const integral. 441 Diag(Loc, diag::err_member_initialization, 442 II->getName(), Init->getSourceRange()); 443 InvalidDecl = true; 444 } 445 446 } else { 447 // not static member. 448 Diag(Loc, diag::err_member_initialization, 449 II->getName(), Init->getSourceRange()); 450 InvalidDecl = true; 451 } 452 } 453 454 if (InvalidDecl) 455 Member->setInvalidDecl(); 456 457 if (isInstField) { 458 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 459 return LastInGroup; 460 } 461 return Member; 462} 463 464void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 465 DeclTy *TagDecl, 466 SourceLocation LBrac, 467 SourceLocation RBrac) { 468 ActOnFields(S, RLoc, TagDecl, 469 (DeclTy**)FieldCollector->getCurFields(), 470 FieldCollector->getCurNumFields(), LBrac, RBrac); 471} 472 473void Sema::ActOnFinishCXXClassDef(DeclTy *D,SourceLocation RBrace) { 474 Decl *Dcl = static_cast<Decl *>(D); 475 assert(isa<CXXRecordDecl>(Dcl) && 476 "Invalid parameter, expected CXXRecordDecl"); 477 FieldCollector->FinishClass(); 478 PopDeclContext(); 479} 480 481//===----------------------------------------------------------------------===// 482// Namespace Handling 483//===----------------------------------------------------------------------===// 484 485/// ActOnStartNamespaceDef - This is called at the start of a namespace 486/// definition. 487Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 488 SourceLocation IdentLoc, 489 IdentifierInfo *II, 490 SourceLocation LBrace) { 491 NamespaceDecl *Namespc = 492 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 493 Namespc->setLBracLoc(LBrace); 494 495 Scope *DeclRegionScope = NamespcScope->getParent(); 496 497 if (II) { 498 // C++ [namespace.def]p2: 499 // The identifier in an original-namespace-definition shall not have been 500 // previously defined in the declarative region in which the 501 // original-namespace-definition appears. The identifier in an 502 // original-namespace-definition is the name of the namespace. Subsequently 503 // in that declarative region, it is treated as an original-namespace-name. 504 505 Decl *PrevDecl = 506 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 507 /*enableLazyBuiltinCreation=*/false); 508 509 if (PrevDecl && 510 IdResolver.isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 511 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 512 // This is an extended namespace definition. 513 // Attach this namespace decl to the chain of extended namespace 514 // definitions. 515 NamespaceDecl *NextNS = OrigNS; 516 while (NextNS->getNextNamespace()) 517 NextNS = NextNS->getNextNamespace(); 518 519 NextNS->setNextNamespace(Namespc); 520 Namespc->setOriginalNamespace(OrigNS); 521 522 // We won't add this decl to the current scope. We want the namespace 523 // name to return the original namespace decl during a name lookup. 524 } else { 525 // This is an invalid name redefinition. 526 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 527 Namespc->getName()); 528 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 529 Namespc->setInvalidDecl(); 530 // Continue on to push Namespc as current DeclContext and return it. 531 } 532 } else { 533 // This namespace name is declared for the first time. 534 PushOnScopeChains(Namespc, DeclRegionScope); 535 } 536 } 537 else { 538 // FIXME: Handle anonymous namespaces 539 } 540 541 // Although we could have an invalid decl (i.e. the namespace name is a 542 // redefinition), push it as current DeclContext and try to continue parsing. 543 PushDeclContext(Namespc->getOriginalNamespace()); 544 return Namespc; 545} 546 547/// ActOnFinishNamespaceDef - This callback is called after a namespace is 548/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 549void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 550 Decl *Dcl = static_cast<Decl *>(D); 551 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 552 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 553 Namespc->setRBracLoc(RBrace); 554 PopDeclContext(); 555} 556