SemaDeclCXX.cpp revision 914701ed49f31323176a784b49df05a0d177d1ad
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 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 ValueDecl *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/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 261/// one entry in the base class list of a class specifier, for 262/// example: 263/// class foo : public bar, virtual private baz { 264/// 'public bar' and 'virtual private baz' are each base-specifiers. 265void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 266 bool Virtual, AccessSpecifier Access, 267 TypeTy *basetype, SourceLocation BaseLoc) { 268 RecordDecl *Decl = (RecordDecl*)classdecl; 269 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 270 271 // Base specifiers must be record types. 272 if (!BaseType->isRecordType()) { 273 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 274 return; 275 } 276 277 // C++ [class.union]p1: 278 // A union shall not be used as a base class. 279 if (BaseType->isUnionType()) { 280 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 281 return; 282 } 283 284 // C++ [class.union]p1: 285 // A union shall not have base classes. 286 if (Decl->isUnion()) { 287 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 288 SpecifierRange); 289 Decl->setInvalidDecl(); 290 return; 291 } 292 293 // C++ [class.derived]p2: 294 // The class-name in a base-specifier shall not be an incompletely 295 // defined class. 296 if (BaseType->isIncompleteType()) { 297 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 298 return; 299 } 300 301 // FIXME: C++ [class.mi]p3: 302 // A class shall not be specified as a direct base class of a 303 // derived class more than once. 304 305 // FIXME: Attach base class to the record. 306} 307 308//===----------------------------------------------------------------------===// 309// C++ class member Handling 310//===----------------------------------------------------------------------===// 311 312/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 313/// definition, when on C++. 314void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 315 Decl *Dcl = static_cast<Decl *>(D); 316 PushDeclContext(cast<CXXRecordDecl>(Dcl)); 317 FieldCollector->StartClass(); 318} 319 320/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 321/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 322/// bitfield width if there is one and 'InitExpr' specifies the initializer if 323/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 324/// declarators on it. 325/// 326/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 327/// an instance field is declared, a new CXXFieldDecl is created but the method 328/// does *not* return it; it returns LastInGroup instead. The other C++ members 329/// (which are all ScopedDecls) are returned after appending them to 330/// LastInGroup. 331Sema::DeclTy * 332Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 333 ExprTy *BW, ExprTy *InitExpr, 334 DeclTy *LastInGroup) { 335 const DeclSpec &DS = D.getDeclSpec(); 336 IdentifierInfo *II = D.getIdentifier(); 337 Expr *BitWidth = static_cast<Expr*>(BW); 338 Expr *Init = static_cast<Expr*>(InitExpr); 339 SourceLocation Loc = D.getIdentifierLoc(); 340 341 // C++ 9.2p6: A member shall not be declared to have automatic storage 342 // duration (auto, register) or with the extern storage-class-specifier. 343 switch (DS.getStorageClassSpec()) { 344 case DeclSpec::SCS_unspecified: 345 case DeclSpec::SCS_typedef: 346 case DeclSpec::SCS_static: 347 // FALL THROUGH. 348 break; 349 default: 350 if (DS.getStorageClassSpecLoc().isValid()) 351 Diag(DS.getStorageClassSpecLoc(), 352 diag::err_storageclass_invalid_for_member); 353 else 354 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 355 D.getMutableDeclSpec().ClearStorageClassSpecs(); 356 } 357 358 QualType T = GetTypeForDeclarator(D, S); 359 360 // T->isFunctionType() is used instead of D.isFunctionDeclarator() to cover 361 // this case: 362 // 363 // typedef int f(); 364 // f a; 365 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 366 !T->isFunctionType()); 367 368 Decl *Member; 369 bool InvalidDecl = false; 370 371 if (isInstField) 372 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 373 else 374 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 375 376 if (!Member) return LastInGroup; 377 378 assert(II || isInstField && "No identifier for non-field ?"); 379 380 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 381 // specific methods. Use a wrapper class that can be used with all C++ class 382 // member decls. 383 CXXClassMemberWrapper(Member).setAccess(AS); 384 385 if (BitWidth) { 386 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 387 // constant-expression be a value equal to zero. 388 // FIXME: Check this. 389 390 if (D.isFunctionDeclarator()) { 391 // FIXME: Emit diagnostic about only constructors taking base initializers 392 // or something similar, when constructor support is in place. 393 Diag(Loc, diag::err_not_bitfield_type, 394 II->getName(), BitWidth->getSourceRange()); 395 InvalidDecl = true; 396 397 } else if (isInstField || isa<FunctionDecl>(Member)) { 398 // An instance field or a function typedef ("typedef int f(); f a;"). 399 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 400 if (!T->isIntegralType()) { 401 Diag(Loc, diag::err_not_integral_type_bitfield, 402 II->getName(), BitWidth->getSourceRange()); 403 InvalidDecl = true; 404 } 405 406 } else if (isa<TypedefDecl>(Member)) { 407 // "cannot declare 'A' to be a bit-field type" 408 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 409 BitWidth->getSourceRange()); 410 InvalidDecl = true; 411 412 } else { 413 assert(isa<CXXClassVarDecl>(Member) && 414 "Didn't we cover all member kinds?"); 415 // C++ 9.6p3: A bit-field shall not be a static member. 416 // "static member 'A' cannot be a bit-field" 417 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 418 BitWidth->getSourceRange()); 419 InvalidDecl = true; 420 } 421 } 422 423 if (Init) { 424 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 425 // if it declares a static member of const integral or const enumeration 426 // type. 427 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 428 // ...static member of... 429 CVD->setInit(Init); 430 // ...const integral or const enumeration type. 431 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 432 CVD->getType()->isIntegralType()) { 433 // constant-initializer 434 if (CheckForConstantInitializer(Init, CVD->getType())) 435 InvalidDecl = true; 436 437 } else { 438 // not const integral. 439 Diag(Loc, diag::err_member_initialization, 440 II->getName(), Init->getSourceRange()); 441 InvalidDecl = true; 442 } 443 444 } else { 445 // not static member. 446 Diag(Loc, diag::err_member_initialization, 447 II->getName(), Init->getSourceRange()); 448 InvalidDecl = true; 449 } 450 } 451 452 if (InvalidDecl) 453 Member->setInvalidDecl(); 454 455 if (isInstField) { 456 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 457 return LastInGroup; 458 } 459 return Member; 460} 461 462void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 463 DeclTy *TagDecl, 464 SourceLocation LBrac, 465 SourceLocation RBrac) { 466 ActOnFields(S, RLoc, TagDecl, 467 (DeclTy**)FieldCollector->getCurFields(), 468 FieldCollector->getCurNumFields(), LBrac, RBrac); 469} 470 471void Sema::ActOnFinishCXXClassDef(DeclTy *D,SourceLocation RBrace) { 472 Decl *Dcl = static_cast<Decl *>(D); 473 assert(isa<CXXRecordDecl>(Dcl) && 474 "Invalid parameter, expected CXXRecordDecl"); 475 FieldCollector->FinishClass(); 476 PopDeclContext(); 477} 478 479//===----------------------------------------------------------------------===// 480// Namespace Handling 481//===----------------------------------------------------------------------===// 482 483/// ActOnStartNamespaceDef - This is called at the start of a namespace 484/// definition. 485Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 486 SourceLocation IdentLoc, 487 IdentifierInfo *II, 488 SourceLocation LBrace) { 489 NamespaceDecl *Namespc = 490 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 491 Namespc->setLBracLoc(LBrace); 492 493 Scope *DeclRegionScope = NamespcScope->getParent(); 494 495 if (II) { 496 // C++ [namespace.def]p2: 497 // The identifier in an original-namespace-definition shall not have been 498 // previously defined in the declarative region in which the 499 // original-namespace-definition appears. The identifier in an 500 // original-namespace-definition is the name of the namespace. Subsequently 501 // in that declarative region, it is treated as an original-namespace-name. 502 503 Decl *PrevDecl = 504 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 505 /*enableLazyBuiltinCreation=*/false); 506 507 if (PrevDecl && 508 IdResolver.isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 509 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 510 // This is an extended namespace definition. 511 // Attach this namespace decl to the chain of extended namespace 512 // definitions. 513 NamespaceDecl *NextNS = OrigNS; 514 while (NextNS->getNextNamespace()) 515 NextNS = NextNS->getNextNamespace(); 516 517 NextNS->setNextNamespace(Namespc); 518 Namespc->setOriginalNamespace(OrigNS); 519 520 // We won't add this decl to the current scope. We want the namespace 521 // name to return the original namespace decl during a name lookup. 522 } else { 523 // This is an invalid name redefinition. 524 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 525 Namespc->getName()); 526 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 527 Namespc->setInvalidDecl(); 528 // Continue on to push Namespc as current DeclContext and return it. 529 } 530 } else { 531 // This namespace name is declared for the first time. 532 PushOnScopeChains(Namespc, DeclRegionScope); 533 } 534 } 535 else { 536 // FIXME: Handle anonymous namespaces 537 } 538 539 // Although we could have an invalid decl (i.e. the namespace name is a 540 // redefinition), push it as current DeclContext and try to continue parsing. 541 PushDeclContext(Namespc->getOriginalNamespace()); 542 return Namespc; 543} 544 545/// ActOnFinishNamespaceDef - This callback is called after a namespace is 546/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 547void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 548 Decl *Dcl = static_cast<Decl *>(D); 549 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 550 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 551 Namespc->setRBracLoc(RBrace); 552 PopDeclContext(); 553} 554