blob: 53051ff57fb894c182b7658a16c77c213c55c127 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ 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"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner8123a952008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000025#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner8123a952008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattner9e979552008-04-12 23:52:44 +000033namespace {
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
Chris Lattnerb77792e2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000043
Chris Lattner9e979552008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000051 };
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000060 }
61
Chris Lattner9e979552008-04-12 23:52:44 +000062 /// 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) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000067 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());
Steve Naroff248a7532008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
85 diag::err_param_default_argument_references_local,
86 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattner9e979552008-04-12 23:52:44 +000087 }
Chris Lattner8123a952008-04-10 02:22:51 +000088
Douglas Gregor3996f232008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattner9e979552008-04-12 23:52:44 +000091
Douglas Gregor796da182008-11-04 14:32:21 +000092 /// 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());
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-04-10 02:22:51 +0000101}
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.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000106void
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).
Chris Lattner3d1cee32008-04-08 05:04:30 +0000126 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregoreb704f22008-11-04 13:57:51 +0000127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128 "in default argument");
Chris Lattner3d1cee32008-04-08 05:04:30 +0000129 if (DefaultArgPtr != DefaultArg.get()) {
130 DefaultArg.take();
131 DefaultArg.reset(DefaultArgPtr);
132 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000133 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000134 return;
135 }
136
Chris Lattner8123a952008-04-10 02:22:51 +0000137 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner8123a952008-04-10 02:22:51 +0000139 if (DefaultArgChecker.Visit(DefaultArg.get()))
140 return;
141
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(DefaultArg.take());
144}
145
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000146/// 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
Chris Lattner3d1cee32008-04-08 05:04:30 +0000174// 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}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000260
Douglas Gregorb48fe382008-10-31 09:07:45 +0000261/// 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
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000272/// 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.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000277Sema::BaseResult
278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
279 bool Virtual, AccessSpecifier Access,
280 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000281 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);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000287 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000288 }
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);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000294 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000295 }
296
297 // C++ [class.union]p1:
298 // A union shall not have base classes.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000299 if (Decl->isUnion()) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000300 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
301 SpecifierRange);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000302 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000303 }
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);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000310 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000311 }
312
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000313 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000314 return new CXXBaseSpecifier(SpecifierRange, Virtual,
315 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000316}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000317
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000318/// ActOnBaseSpecifiers - Attach the given base specifiers to the
319/// class, after checking whether there are any duplicate base
320/// classes.
321void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
322 unsigned NumBases) {
323 if (NumBases == 0)
324 return;
325
326 // Used to keep track of which base types we have already seen, so
327 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000328 // that the key is always the unqualified canonical type of the base
329 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000330 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
331
332 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000333 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
334 unsigned NumGoodBases = 0;
335 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000336 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000337 = Context.getCanonicalType(BaseSpecs[idx]->getType());
338 NewBaseType = NewBaseType.getUnqualifiedType();
339
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000340 if (KnownBaseTypes[NewBaseType]) {
341 // C++ [class.mi]p3:
342 // A class shall not be specified as a direct base class of a
343 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000344 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000345 diag::err_duplicate_base_class,
346 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor57c856b2008-10-23 18:13:27 +0000347 BaseSpecs[idx]->getSourceRange());
348
349 // Delete the duplicate base class specifier; we're going to
350 // overwrite its pointer later.
351 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000352 } else {
353 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000354 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
355 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000356 }
357 }
358
359 // Attach the remaining base class specifiers to the derived class.
360 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000361 Decl->setBases(BaseSpecs, NumGoodBases);
362
363 // Delete the remaining (good) base class specifiers, since their
364 // data has been copied into the CXXRecordDecl.
365 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
366 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000367}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000368
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000369//===----------------------------------------------------------------------===//
370// C++ class member Handling
371//===----------------------------------------------------------------------===//
372
373/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
374/// definition, when on C++.
375void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000376 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
377 PushDeclContext(Dcl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000378 FieldCollector->StartClass();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000379
380 if (Dcl->getIdentifier()) {
381 // C++ [class]p2:
382 // [...] The class-name is also inserted into the scope of the
383 // class itself; this is known as the injected-class-name. For
384 // purposes of access checking, the injected-class-name is treated
385 // as if it were a public member name.
386 TypedefDecl *InjectedClassName
387 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
388 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
389 PushOnScopeChains(InjectedClassName, S);
390 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000391}
392
393/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
394/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
395/// bitfield width if there is one and 'InitExpr' specifies the initializer if
396/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
397/// declarators on it.
398///
399/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
400/// an instance field is declared, a new CXXFieldDecl is created but the method
401/// does *not* return it; it returns LastInGroup instead. The other C++ members
402/// (which are all ScopedDecls) are returned after appending them to
403/// LastInGroup.
404Sema::DeclTy *
405Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
406 ExprTy *BW, ExprTy *InitExpr,
407 DeclTy *LastInGroup) {
408 const DeclSpec &DS = D.getDeclSpec();
409 IdentifierInfo *II = D.getIdentifier();
410 Expr *BitWidth = static_cast<Expr*>(BW);
411 Expr *Init = static_cast<Expr*>(InitExpr);
412 SourceLocation Loc = D.getIdentifierLoc();
413
414 // C++ 9.2p6: A member shall not be declared to have automatic storage
415 // duration (auto, register) or with the extern storage-class-specifier.
416 switch (DS.getStorageClassSpec()) {
417 case DeclSpec::SCS_unspecified:
418 case DeclSpec::SCS_typedef:
419 case DeclSpec::SCS_static:
420 // FALL THROUGH.
421 break;
422 default:
423 if (DS.getStorageClassSpecLoc().isValid())
424 Diag(DS.getStorageClassSpecLoc(),
425 diag::err_storageclass_invalid_for_member);
426 else
427 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
428 D.getMutableDeclSpec().ClearStorageClassSpecs();
429 }
430
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000431 bool isFunc = D.isFunctionDeclarator();
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000432 if (!isFunc &&
433 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
434 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000435 // Check also for this case:
436 //
437 // typedef int f();
438 // f a;
439 //
440 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
441 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
442 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000443
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000444 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000445 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000446
447 Decl *Member;
448 bool InvalidDecl = false;
449
450 if (isInstField)
451 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
452 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000453 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000454
455 if (!Member) return LastInGroup;
456
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000457 assert((II || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000458
459 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
460 // specific methods. Use a wrapper class that can be used with all C++ class
461 // member decls.
462 CXXClassMemberWrapper(Member).setAccess(AS);
463
Douglas Gregor64bffa92008-11-05 16:20:31 +0000464 // C++ [dcl.init.aggr]p1:
465 // An aggregate is an array or a class (clause 9) with [...] no
466 // private or protected non-static data members (clause 11).
467 if (isInstField && (AS == AS_private || AS == AS_protected))
468 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
469
470 // FIXME: If the member is a virtual function, mark it its class as
471 // a non-aggregate.
472
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000473 if (BitWidth) {
474 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
475 // constant-expression be a value equal to zero.
476 // FIXME: Check this.
477
478 if (D.isFunctionDeclarator()) {
479 // FIXME: Emit diagnostic about only constructors taking base initializers
480 // or something similar, when constructor support is in place.
481 Diag(Loc, diag::err_not_bitfield_type,
482 II->getName(), BitWidth->getSourceRange());
483 InvalidDecl = true;
484
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000485 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000486 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000487 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000488 Diag(Loc, diag::err_not_integral_type_bitfield,
489 II->getName(), BitWidth->getSourceRange());
490 InvalidDecl = true;
491 }
492
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000493 } else if (isa<FunctionDecl>(Member)) {
494 // A function typedef ("typedef int f(); f a;").
495 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
496 Diag(Loc, diag::err_not_integral_type_bitfield,
497 II->getName(), BitWidth->getSourceRange());
498 InvalidDecl = true;
499
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000500 } else if (isa<TypedefDecl>(Member)) {
501 // "cannot declare 'A' to be a bit-field type"
502 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
503 BitWidth->getSourceRange());
504 InvalidDecl = true;
505
506 } else {
507 assert(isa<CXXClassVarDecl>(Member) &&
508 "Didn't we cover all member kinds?");
509 // C++ 9.6p3: A bit-field shall not be a static member.
510 // "static member 'A' cannot be a bit-field"
511 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
512 BitWidth->getSourceRange());
513 InvalidDecl = true;
514 }
515 }
516
517 if (Init) {
518 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
519 // if it declares a static member of const integral or const enumeration
520 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000521 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
522 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000523 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000524 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000525 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
526 CVD->getType()->isIntegralType()) {
527 // constant-initializer
528 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000529 InvalidDecl = true;
530
531 } else {
532 // not const integral.
533 Diag(Loc, diag::err_member_initialization,
534 II->getName(), Init->getSourceRange());
535 InvalidDecl = true;
536 }
537
538 } else {
539 // not static member.
540 Diag(Loc, diag::err_member_initialization,
541 II->getName(), Init->getSourceRange());
542 InvalidDecl = true;
543 }
544 }
545
546 if (InvalidDecl)
547 Member->setInvalidDecl();
548
549 if (isInstField) {
550 FieldCollector->Add(cast<CXXFieldDecl>(Member));
551 return LastInGroup;
552 }
553 return Member;
554}
555
Douglas Gregor7ad83902008-11-05 04:29:56 +0000556/// ActOnMemInitializer - Handle a C++ member initializer.
557Sema::MemInitResult
558Sema::ActOnMemInitializer(DeclTy *ConstructorD,
559 Scope *S,
560 IdentifierInfo *MemberOrBase,
561 SourceLocation IdLoc,
562 SourceLocation LParenLoc,
563 ExprTy **Args, unsigned NumArgs,
564 SourceLocation *CommaLocs,
565 SourceLocation RParenLoc) {
566 CXXConstructorDecl *Constructor
567 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
568 if (!Constructor) {
569 // The user wrote a constructor initializer on a function that is
570 // not a C++ constructor. Ignore the error for now, because we may
571 // have more member initializers coming; we'll diagnose it just
572 // once in ActOnMemInitializers.
573 return true;
574 }
575
576 CXXRecordDecl *ClassDecl = Constructor->getParent();
577
578 // C++ [class.base.init]p2:
579 // Names in a mem-initializer-id are looked up in the scope of the
580 // constructor’s class and, if not found in that scope, are looked
581 // up in the scope containing the constructor’s
582 // definition. [Note: if the constructor’s class contains a member
583 // with the same name as a direct or virtual base class of the
584 // class, a mem-initializer-id naming the member or base class and
585 // composed of a single identifier refers to the class member. A
586 // mem-initializer-id for the hidden base class may be specified
587 // using a qualified name. ]
588 // Look for a member, first.
589 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
590
591 // FIXME: Handle members of an anonymous union.
592
593 if (Member) {
594 // FIXME: Perform direct initialization of the member.
595 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
596 }
597
598 // It didn't name a member, so see if it names a class.
599 TypeTy *BaseTy = isTypeName(*MemberOrBase, S);
600 if (!BaseTy)
601 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
602 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
603
604 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
605 if (!BaseType->isRecordType())
606 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
607 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
608
609 // C++ [class.base.init]p2:
610 // [...] Unless the mem-initializer-id names a nonstatic data
611 // member of the constructor’s class or a direct or virtual base
612 // of that class, the mem-initializer is ill-formed. A
613 // mem-initializer-list can initialize a base class using any
614 // name that denotes that base class type.
615
616 // First, check for a direct base class.
617 const CXXBaseSpecifier *DirectBaseSpec = 0;
618 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
619 Base != ClassDecl->bases_end(); ++Base) {
620 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
621 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
622 // We found a direct base of this type. That's what we're
623 // initializing.
624 DirectBaseSpec = &*Base;
625 break;
626 }
627 }
628
629 // Check for a virtual base class.
630 // FIXME: We might be able to short-circuit this if we know in
631 // advance that there are no virtual bases.
632 const CXXBaseSpecifier *VirtualBaseSpec = 0;
633 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
634 // We haven't found a base yet; search the class hierarchy for a
635 // virtual base class.
636 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
637 /*DetectVirtual=*/false);
638 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
639 for (BasePaths::paths_iterator Path = Paths.begin();
640 Path != Paths.end(); ++Path) {
641 if (Path->back().Base->isVirtual()) {
642 VirtualBaseSpec = Path->back().Base;
643 break;
644 }
645 }
646 }
647 }
648
649 // C++ [base.class.init]p2:
650 // If a mem-initializer-id is ambiguous because it designates both
651 // a direct non-virtual base class and an inherited virtual base
652 // class, the mem-initializer is ill-formed.
653 if (DirectBaseSpec && VirtualBaseSpec)
654 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
655 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
656
657 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
658}
659
660
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000661void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
662 DeclTy *TagDecl,
663 SourceLocation LBrac,
664 SourceLocation RBrac) {
665 ActOnFields(S, RLoc, TagDecl,
666 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000667 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000668}
669
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000670/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
671/// special functions, such as the default constructor, copy
672/// constructor, or destructor, to the given C++ class (C++
673/// [special]p1). This routine can only be executed just before the
674/// definition of the class is complete.
675void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
676 if (!ClassDecl->hasUserDeclaredConstructor()) {
677 // C++ [class.ctor]p5:
678 // A default constructor for a class X is a constructor of class X
679 // that can be called without an argument. If there is no
680 // user-declared constructor for class X, a default constructor is
681 // implicitly declared. An implicitly-declared default constructor
682 // is an inline public member of its class.
683 CXXConstructorDecl *DefaultCon =
684 CXXConstructorDecl::Create(Context, ClassDecl,
685 ClassDecl->getLocation(),
686 ClassDecl->getIdentifier(),
687 Context.getFunctionType(Context.VoidTy,
688 0, 0, false, 0),
689 /*isExplicit=*/false,
690 /*isInline=*/true,
691 /*isImplicitlyDeclared=*/true);
692 DefaultCon->setAccess(AS_public);
693 ClassDecl->addConstructor(Context, DefaultCon);
694 }
695
696 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
697 // C++ [class.copy]p4:
698 // If the class definition does not explicitly declare a copy
699 // constructor, one is declared implicitly.
700
701 // C++ [class.copy]p5:
702 // The implicitly-declared copy constructor for a class X will
703 // have the form
704 //
705 // X::X(const X&)
706 //
707 // if
708 bool HasConstCopyConstructor = true;
709
710 // -- each direct or virtual base class B of X has a copy
711 // constructor whose first parameter is of type const B& or
712 // const volatile B&, and
713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
714 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
715 const CXXRecordDecl *BaseClassDecl
716 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
717 HasConstCopyConstructor
718 = BaseClassDecl->hasConstCopyConstructor(Context);
719 }
720
721 // -- for all the nonstatic data members of X that are of a
722 // class type M (or array thereof), each such class type
723 // has a copy constructor whose first parameter is of type
724 // const M& or const volatile M&.
725 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
726 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
727 QualType FieldType = (*Field)->getType();
728 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
729 FieldType = Array->getElementType();
730 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
731 const CXXRecordDecl *FieldClassDecl
732 = cast<CXXRecordDecl>(FieldClassType->getDecl());
733 HasConstCopyConstructor
734 = FieldClassDecl->hasConstCopyConstructor(Context);
735 }
736 }
737
738 // Otherwise, the implicitly declared copy constructor will have
739 // the form
740 //
741 // X::X(X&)
742 QualType ArgType = Context.getTypeDeclType(ClassDecl);
743 if (HasConstCopyConstructor)
744 ArgType = ArgType.withConst();
745 ArgType = Context.getReferenceType(ArgType);
746
747 // An implicitly-declared copy constructor is an inline public
748 // member of its class.
749 CXXConstructorDecl *CopyConstructor
750 = CXXConstructorDecl::Create(Context, ClassDecl,
751 ClassDecl->getLocation(),
752 ClassDecl->getIdentifier(),
753 Context.getFunctionType(Context.VoidTy,
754 &ArgType, 1,
755 false, 0),
756 /*isExplicit=*/false,
757 /*isInline=*/true,
758 /*isImplicitlyDeclared=*/true);
759 CopyConstructor->setAccess(AS_public);
760
761 // Add the parameter to the constructor.
762 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
763 ClassDecl->getLocation(),
764 /*IdentifierInfo=*/0,
765 ArgType, VarDecl::None, 0, 0);
766 CopyConstructor->setParams(&FromParam, 1);
767
768 ClassDecl->addConstructor(Context, CopyConstructor);
769 }
770
771 // FIXME: Implicit destructor
772 // FIXME: Implicit copy assignment operator
773}
774
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000775void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000776 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000777 FieldCollector->FinishClass();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000778 AddImplicitlyDeclaredMembersToClass(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000779 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000780
781 // Everything, including inline method definitions, have been parsed.
782 // Let the consumer know of the new TagDecl definition.
783 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000784}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000785
Douglas Gregorb48fe382008-10-31 09:07:45 +0000786/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
787/// the declaration of the given C++ constructor ConDecl that was
788/// built from declarator D. This routine is responsible for checking
789/// that the newly-created constructor declaration is well-formed and
790/// for recording it in the C++ class. Example:
791///
792/// @code
793/// class X {
794/// X(); // X::X() will be the ConDecl.
795/// };
796/// @endcode
797Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
798 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregor60d62c22008-10-31 16:23:19 +0000799
800 // Check default arguments on the constructor
801 CheckCXXDefaultArguments(ConDecl);
802
Douglas Gregor030ff0c2008-10-31 20:25:05 +0000803 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
804 if (!ClassDecl) {
805 ConDecl->setInvalidDecl();
806 return ConDecl;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000807 }
808
Douglas Gregor030ff0c2008-10-31 20:25:05 +0000809 // Make sure this constructor is an overload of the existing
810 // constructors.
811 OverloadedFunctionDecl::function_iterator MatchedDecl;
812 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
813 Diag(ConDecl->getLocation(),
814 diag::err_constructor_redeclared,
815 SourceRange(ConDecl->getLocation()));
816 Diag((*MatchedDecl)->getLocation(),
817 diag::err_previous_declaration,
818 SourceRange((*MatchedDecl)->getLocation()));
819 ConDecl->setInvalidDecl();
820 return ConDecl;
821 }
822
823
824 // C++ [class.copy]p3:
825 // A declaration of a constructor for a class X is ill-formed if
826 // its first parameter is of type (optionally cv-qualified) X and
827 // either there are no other parameters or else all other
828 // parameters have default arguments.
829 if ((ConDecl->getNumParams() == 1) ||
830 (ConDecl->getNumParams() > 1 &&
831 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
832 QualType ParamType = ConDecl->getParamDecl(0)->getType();
833 QualType ClassTy = Context.getTagDeclType(
834 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
835 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
836 Diag(ConDecl->getLocation(),
837 diag::err_constructor_byvalue_arg,
838 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
839 ConDecl->setInvalidDecl();
840 return 0;
841 }
842 }
843
844 // Add this constructor to the set of constructors of the current
845 // class.
846 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000847 return (DeclTy *)ConDecl;
848}
849
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000850//===----------------------------------------------------------------------===//
851// Namespace Handling
852//===----------------------------------------------------------------------===//
853
854/// ActOnStartNamespaceDef - This is called at the start of a namespace
855/// definition.
856Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
857 SourceLocation IdentLoc,
858 IdentifierInfo *II,
859 SourceLocation LBrace) {
860 NamespaceDecl *Namespc =
861 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
862 Namespc->setLBracLoc(LBrace);
863
864 Scope *DeclRegionScope = NamespcScope->getParent();
865
866 if (II) {
867 // C++ [namespace.def]p2:
868 // The identifier in an original-namespace-definition shall not have been
869 // previously defined in the declarative region in which the
870 // original-namespace-definition appears. The identifier in an
871 // original-namespace-definition is the name of the namespace. Subsequently
872 // in that declarative region, it is treated as an original-namespace-name.
873
874 Decl *PrevDecl =
Argyrios Kyrtzidis154d8e22008-10-14 18:28:48 +0000875 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000876 /*enableLazyBuiltinCreation=*/false);
877
Argyrios Kyrtzidis2fac6262008-09-10 02:11:07 +0000878 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000879 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
880 // This is an extended namespace definition.
881 // Attach this namespace decl to the chain of extended namespace
882 // definitions.
883 NamespaceDecl *NextNS = OrigNS;
884 while (NextNS->getNextNamespace())
885 NextNS = NextNS->getNextNamespace();
886
887 NextNS->setNextNamespace(Namespc);
888 Namespc->setOriginalNamespace(OrigNS);
889
890 // We won't add this decl to the current scope. We want the namespace
891 // name to return the original namespace decl during a name lookup.
892 } else {
893 // This is an invalid name redefinition.
894 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
895 Namespc->getName());
896 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
897 Namespc->setInvalidDecl();
898 // Continue on to push Namespc as current DeclContext and return it.
899 }
900 } else {
901 // This namespace name is declared for the first time.
902 PushOnScopeChains(Namespc, DeclRegionScope);
903 }
904 }
905 else {
906 // FIXME: Handle anonymous namespaces
907 }
908
909 // Although we could have an invalid decl (i.e. the namespace name is a
910 // redefinition), push it as current DeclContext and try to continue parsing.
911 PushDeclContext(Namespc->getOriginalNamespace());
912 return Namespc;
913}
914
915/// ActOnFinishNamespaceDef - This callback is called after a namespace is
916/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
917void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
918 Decl *Dcl = static_cast<Decl *>(D);
919 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
920 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
921 Namespc->setRBracLoc(RBrace);
922 PopDeclContext();
923}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000924
925
926/// AddCXXDirectInitializerToDecl - This action is called immediately after
927/// ActOnDeclarator, when a C++ direct initializer is present.
928/// e.g: "int x(1);"
929void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
930 ExprTy **ExprTys, unsigned NumExprs,
931 SourceLocation *CommaLocs,
932 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000933 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000934 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000935
936 // If there is no declaration, there was an error parsing it. Just ignore
937 // the initializer.
938 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +0000939 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000940 delete static_cast<Expr *>(ExprTys[i]);
941 return;
942 }
943
944 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
945 if (!VDecl) {
946 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
947 RealDecl->setInvalidDecl();
948 return;
949 }
950
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000951 // We will treat direct-initialization as a copy-initialization:
952 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000953 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
954 //
955 // Clients that want to distinguish between the two forms, can check for
956 // direct initializer using VarDecl::hasCXXDirectInitializer().
957 // A major benefit is that clients that don't particularly care about which
958 // exactly form was it (like the CodeGen) can handle both cases without
959 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000960
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000961 // C++ 8.5p11:
962 // The form of initialization (using parentheses or '=') is generally
963 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000964 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +0000965 QualType DeclInitType = VDecl->getType();
966 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
967 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000968
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000969 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +0000970 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000971 = PerformInitializationByConstructor(DeclInitType,
972 (Expr **)ExprTys, NumExprs,
973 VDecl->getLocation(),
974 SourceRange(VDecl->getLocation(),
975 RParenLoc),
976 VDecl->getName(),
977 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +0000978 if (!Constructor) {
979 RealDecl->setInvalidDecl();
980 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000981
982 // Let clients know that initialization was done with a direct
983 // initializer.
984 VDecl->setCXXDirectInitializer(true);
985
986 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
987 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000988 return;
989 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000990
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000991 if (NumExprs > 1) {
992 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
993 SourceRange(VDecl->getLocation(), RParenLoc));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000994 RealDecl->setInvalidDecl();
995 return;
996 }
997
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000998 // Let clients know that initialization was done with a direct initializer.
999 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001000
1001 assert(NumExprs == 1 && "Expected 1 expression");
1002 // Set the init expression, handles conversions.
1003 AddInitializerToDecl(Dcl, ExprTys[0]);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001004}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001005
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001006/// PerformInitializationByConstructor - Perform initialization by
1007/// constructor (C++ [dcl.init]p14), which may occur as part of
1008/// direct-initialization or copy-initialization. We are initializing
1009/// an object of type @p ClassType with the given arguments @p
1010/// Args. @p Loc is the location in the source code where the
1011/// initializer occurs (e.g., a declaration, member initializer,
1012/// functional cast, etc.) while @p Range covers the whole
1013/// initialization. @p InitEntity is the entity being initialized,
1014/// which may by the name of a declaration or a type. @p Kind is the
1015/// kind of initialization we're performing, which affects whether
1016/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001017/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001018/// when the initialization fails, emits a diagnostic and returns
1019/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001020CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001021Sema::PerformInitializationByConstructor(QualType ClassType,
1022 Expr **Args, unsigned NumArgs,
1023 SourceLocation Loc, SourceRange Range,
1024 std::string InitEntity,
1025 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001026 const RecordType *ClassRec = ClassType->getAsRecordType();
1027 assert(ClassRec && "Can only initialize a class type here");
1028
1029 // C++ [dcl.init]p14:
1030 //
1031 // If the initialization is direct-initialization, or if it is
1032 // copy-initialization where the cv-unqualified version of the
1033 // source type is the same class as, or a derived class of, the
1034 // class of the destination, constructors are considered. The
1035 // applicable constructors are enumerated (13.3.1.3), and the
1036 // best one is chosen through overload resolution (13.3). The
1037 // constructor so selected is called to initialize the object,
1038 // with the initializer expression(s) as its argument(s). If no
1039 // constructor applies, or the overload resolution is ambiguous,
1040 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001041 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1042 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001043
1044 // Add constructors to the overload set.
1045 OverloadedFunctionDecl *Constructors
1046 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1047 for (OverloadedFunctionDecl::function_iterator Con
1048 = Constructors->function_begin();
1049 Con != Constructors->function_end(); ++Con) {
1050 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1051 if ((Kind == IK_Direct) ||
1052 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1053 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1054 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1055 }
1056
Douglas Gregor18fe5682008-11-03 20:45:27 +00001057 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001058 switch (BestViableFunction(CandidateSet, Best)) {
1059 case OR_Success:
1060 // We found a constructor. Return it.
1061 return cast<CXXConstructorDecl>(Best->Function);
1062
1063 case OR_No_Viable_Function:
1064 if (CandidateSet.empty())
1065 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1066 InitEntity, Range);
1067 else {
1068 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1069 InitEntity, Range);
1070 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1071 }
1072 return 0;
1073
1074 case OR_Ambiguous:
1075 Diag(Loc, diag::err_ovl_ambiguous_init,
1076 InitEntity, Range);
1077 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1078 return 0;
1079 }
1080
1081 return 0;
1082}
1083
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001084/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1085/// determine whether they are reference-related,
1086/// reference-compatible, reference-compatible with added
1087/// qualification, or incompatible, for use in C++ initialization by
1088/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1089/// type, and the first type (T1) is the pointee type of the reference
1090/// type being initialized.
1091Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001092Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1093 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001094 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1095 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1096
1097 T1 = Context.getCanonicalType(T1);
1098 T2 = Context.getCanonicalType(T2);
1099 QualType UnqualT1 = T1.getUnqualifiedType();
1100 QualType UnqualT2 = T2.getUnqualifiedType();
1101
1102 // C++ [dcl.init.ref]p4:
1103 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1104 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1105 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001106 if (UnqualT1 == UnqualT2)
1107 DerivedToBase = false;
1108 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1109 DerivedToBase = true;
1110 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001111 return Ref_Incompatible;
1112
1113 // At this point, we know that T1 and T2 are reference-related (at
1114 // least).
1115
1116 // C++ [dcl.init.ref]p4:
1117 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1118 // reference-related to T2 and cv1 is the same cv-qualification
1119 // as, or greater cv-qualification than, cv2. For purposes of
1120 // overload resolution, cases for which cv1 is greater
1121 // cv-qualification than cv2 are identified as
1122 // reference-compatible with added qualification (see 13.3.3.2).
1123 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1124 return Ref_Compatible;
1125 else if (T1.isMoreQualifiedThan(T2))
1126 return Ref_Compatible_With_Added_Qualification;
1127 else
1128 return Ref_Related;
1129}
1130
1131/// CheckReferenceInit - Check the initialization of a reference
1132/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1133/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001134/// list), and DeclType is the type of the declaration. When ICS is
1135/// non-null, this routine will compute the implicit conversion
1136/// sequence according to C++ [over.ics.ref] and will not produce any
1137/// diagnostics; when ICS is null, it will emit diagnostics when any
1138/// errors are found. Either way, a return value of true indicates
1139/// that there was a failure, a return value of false indicates that
1140/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001141///
1142/// When @p SuppressUserConversions, user-defined conversions are
1143/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001144bool
1145Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001146 ImplicitConversionSequence *ICS,
1147 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001148 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1149
1150 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1151 QualType T2 = Init->getType();
1152
Douglas Gregor15da57e2008-10-29 02:00:59 +00001153 // Compute some basic properties of the types and the initializer.
1154 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001155 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001156 ReferenceCompareResult RefRelationship
1157 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1158
1159 // Most paths end in a failed conversion.
1160 if (ICS)
1161 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001162
1163 // C++ [dcl.init.ref]p5:
1164 // A reference to type “cv1 T1” is initialized by an expression
1165 // of type “cv2 T2” as follows:
1166
1167 // -- If the initializer expression
1168
1169 bool BindsDirectly = false;
1170 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1171 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001172 //
1173 // Note that the bit-field check is skipped if we are just computing
1174 // the implicit conversion sequence (C++ [over.best.ics]p2).
1175 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1176 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001177 BindsDirectly = true;
1178
Douglas Gregor15da57e2008-10-29 02:00:59 +00001179 if (ICS) {
1180 // C++ [over.ics.ref]p1:
1181 // When a parameter of reference type binds directly (8.5.3)
1182 // to an argument expression, the implicit conversion sequence
1183 // is the identity conversion, unless the argument expression
1184 // has a type that is a derived class of the parameter type,
1185 // in which case the implicit conversion sequence is a
1186 // derived-to-base Conversion (13.3.3.1).
1187 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1188 ICS->Standard.First = ICK_Identity;
1189 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1190 ICS->Standard.Third = ICK_Identity;
1191 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1192 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001193 ICS->Standard.ReferenceBinding = true;
1194 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001195
1196 // Nothing more to do: the inaccessibility/ambiguity check for
1197 // derived-to-base conversions is suppressed when we're
1198 // computing the implicit conversion sequence (C++
1199 // [over.best.ics]p2).
1200 return false;
1201 } else {
1202 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001203 // FIXME: Binding to a subobject of the lvalue is going to require
1204 // more AST annotation than this.
1205 ImpCastExprToType(Init, T1);
1206 }
1207 }
1208
1209 // -- has a class type (i.e., T2 is a class type) and can be
1210 // implicitly converted to an lvalue of type “cv3 T3,”
1211 // where “cv1 T1” is reference-compatible with “cv3 T3”
1212 // 92) (this conversion is selected by enumerating the
1213 // applicable conversion functions (13.3.1.6) and choosing
1214 // the best one through overload resolution (13.3)),
1215 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor15da57e2008-10-29 02:00:59 +00001216 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001217
1218 if (BindsDirectly) {
1219 // C++ [dcl.init.ref]p4:
1220 // [...] In all cases where the reference-related or
1221 // reference-compatible relationship of two types is used to
1222 // establish the validity of a reference binding, and T1 is a
1223 // base class of T2, a program that necessitates such a binding
1224 // is ill-formed if T1 is an inaccessible (clause 11) or
1225 // ambiguous (10.2) base class of T2.
1226 //
1227 // Note that we only check this condition when we're allowed to
1228 // complain about errors, because we should not be checking for
1229 // ambiguity (or inaccessibility) unless the reference binding
1230 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001231 if (DerivedToBase)
1232 return CheckDerivedToBaseConversion(T2, T1,
1233 Init->getSourceRange().getBegin(),
1234 Init->getSourceRange());
1235 else
1236 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001237 }
1238
1239 // -- Otherwise, the reference shall be to a non-volatile const
1240 // type (i.e., cv1 shall be const).
1241 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001242 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001243 Diag(Init->getSourceRange().getBegin(),
1244 diag::err_not_reference_to_const_init,
1245 T1.getAsString(),
1246 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1247 T2.getAsString(), Init->getSourceRange());
1248 return true;
1249 }
1250
1251 // -- If the initializer expression is an rvalue, with T2 a
1252 // class type, and “cv1 T1” is reference-compatible with
1253 // “cv2 T2,” the reference is bound in one of the
1254 // following ways (the choice is implementation-defined):
1255 //
1256 // -- The reference is bound to the object represented by
1257 // the rvalue (see 3.10) or to a sub-object within that
1258 // object.
1259 //
1260 // -- A temporary of type “cv1 T2” [sic] is created, and
1261 // a constructor is called to copy the entire rvalue
1262 // object into the temporary. The reference is bound to
1263 // the temporary or to a sub-object within the
1264 // temporary.
1265 //
1266 //
1267 // The constructor that would be used to make the copy
1268 // shall be callable whether or not the copy is actually
1269 // done.
1270 //
1271 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1272 // freedom, so we will always take the first option and never build
1273 // a temporary in this case. FIXME: We will, however, have to check
1274 // for the presence of a copy constructor in C++98/03 mode.
1275 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001276 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1277 if (ICS) {
1278 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1279 ICS->Standard.First = ICK_Identity;
1280 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1281 ICS->Standard.Third = ICK_Identity;
1282 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1283 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001284 ICS->Standard.ReferenceBinding = true;
1285 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001286 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001287 // FIXME: Binding to a subobject of the rvalue is going to require
1288 // more AST annotation than this.
1289 ImpCastExprToType(Init, T1);
1290 }
1291 return false;
1292 }
1293
1294 // -- Otherwise, a temporary of type “cv1 T1” is created and
1295 // initialized from the initializer expression using the
1296 // rules for a non-reference copy initialization (8.5). The
1297 // reference is then bound to the temporary. If T1 is
1298 // reference-related to T2, cv1 must be the same
1299 // cv-qualification as, or greater cv-qualification than,
1300 // cv2; otherwise, the program is ill-formed.
1301 if (RefRelationship == Ref_Related) {
1302 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1303 // we would be reference-compatible or reference-compatible with
1304 // added qualification. But that wasn't the case, so the reference
1305 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001306 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001307 Diag(Init->getSourceRange().getBegin(),
1308 diag::err_reference_init_drops_quals,
1309 T1.getAsString(),
1310 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1311 T2.getAsString(), Init->getSourceRange());
1312 return true;
1313 }
1314
1315 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001316 if (ICS) {
1317 /// C++ [over.ics.ref]p2:
1318 ///
1319 /// When a parameter of reference type is not bound directly to
1320 /// an argument expression, the conversion sequence is the one
1321 /// required to convert the argument expression to the
1322 /// underlying type of the reference according to
1323 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1324 /// to copy-initializing a temporary of the underlying type with
1325 /// the argument expression. Any difference in top-level
1326 /// cv-qualification is subsumed by the initialization itself
1327 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001328 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001329 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1330 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001331 return PerformImplicitConversion(Init, T1);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001332 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001333}