blob: 1b189f87fcba8482c653a8452ef159270615b105 [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(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000078 << Param->getDeclName() << 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(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000086 << VDecl->getDeclName() << 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(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000098 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) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000117 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()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
166 << Param->getDefaultArg()->getSourceRange();
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000167 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(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000198 diag::err_param_default_argument_redefinition)
199 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000200 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000201 } 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(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000236 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000237 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000238 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.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
266 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000267 CXXRecordDecl *CurDecl;
268 if (SS) {
269 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
270 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
271 } else
272 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
273
274 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000275 return &II == CurDecl->getIdentifier();
276 else
277 return false;
278}
279
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000280/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
281/// one entry in the base class list of a class specifier, for
282/// example:
283/// class foo : public bar, virtual private baz {
284/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000285Sema::BaseResult
286Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
287 bool Virtual, AccessSpecifier Access,
288 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000289 RecordDecl *Decl = (RecordDecl*)classdecl;
290 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
291
292 // Base specifiers must be record types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 if (!BaseType->isRecordType())
294 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000295
296 // C++ [class.union]p1:
297 // A union shall not be used as a base class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000298 if (BaseType->isUnionType())
299 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000300
301 // C++ [class.union]p1:
302 // A union shall not have base classes.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000303 if (Decl->isUnion())
304 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
305 << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000306
307 // C++ [class.derived]p2:
308 // The class-name in a base-specifier shall not be an incompletely
309 // defined class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 if (BaseType->isIncompleteType())
311 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000312
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000313 // If the base class is polymorphic, the new one is, too.
314 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
315 assert(BaseDecl && "Record type has no declaration");
316 BaseDecl = BaseDecl->getDefinition(Context);
317 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000318 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000319 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000320
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000321 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000322 return new CXXBaseSpecifier(SpecifierRange, Virtual,
323 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000324}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000325
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000326/// ActOnBaseSpecifiers - Attach the given base specifiers to the
327/// class, after checking whether there are any duplicate base
328/// classes.
329void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
330 unsigned NumBases) {
331 if (NumBases == 0)
332 return;
333
334 // Used to keep track of which base types we have already seen, so
335 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000336 // that the key is always the unqualified canonical type of the base
337 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000338 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
339
340 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000341 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
342 unsigned NumGoodBases = 0;
343 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000344 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000345 = Context.getCanonicalType(BaseSpecs[idx]->getType());
346 NewBaseType = NewBaseType.getUnqualifiedType();
347
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000348 if (KnownBaseTypes[NewBaseType]) {
349 // C++ [class.mi]p3:
350 // A class shall not be specified as a direct base class of a
351 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000352 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000353 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000354 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000355 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000356
357 // Delete the duplicate base class specifier; we're going to
358 // overwrite its pointer later.
359 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000360 } else {
361 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000362 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
363 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000364 }
365 }
366
367 // Attach the remaining base class specifiers to the derived class.
368 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000369 Decl->setBases(BaseSpecs, NumGoodBases);
370
371 // Delete the remaining (good) base class specifiers, since their
372 // data has been copied into the CXXRecordDecl.
373 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
374 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000375}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000376
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000377//===----------------------------------------------------------------------===//
378// C++ class member Handling
379//===----------------------------------------------------------------------===//
380
381/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
382/// definition, when on C++.
383void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000384 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Douglas Gregor44b43212008-12-11 16:49:14 +0000385 PushDeclContext(S, Dcl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000386 FieldCollector->StartClass();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000387
388 if (Dcl->getIdentifier()) {
389 // C++ [class]p2:
390 // [...] The class-name is also inserted into the scope of the
391 // class itself; this is known as the injected-class-name. For
392 // purposes of access checking, the injected-class-name is treated
393 // as if it were a public member name.
Douglas Gregor55c60952008-11-10 14:41:22 +0000394 PushOnScopeChains(Dcl, S);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000395 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000396}
397
398/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
399/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
400/// bitfield width if there is one and 'InitExpr' specifies the initializer if
401/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
402/// declarators on it.
403///
404/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
405/// an instance field is declared, a new CXXFieldDecl is created but the method
406/// does *not* return it; it returns LastInGroup instead. The other C++ members
407/// (which are all ScopedDecls) are returned after appending them to
408/// LastInGroup.
409Sema::DeclTy *
410Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
411 ExprTy *BW, ExprTy *InitExpr,
412 DeclTy *LastInGroup) {
413 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000414 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000415 Expr *BitWidth = static_cast<Expr*>(BW);
416 Expr *Init = static_cast<Expr*>(InitExpr);
417 SourceLocation Loc = D.getIdentifierLoc();
418
Sebastian Redl669d5d72008-11-14 23:42:31 +0000419 bool isFunc = D.isFunctionDeclarator();
420
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000421 // C++ 9.2p6: A member shall not be declared to have automatic storage
422 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000423 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
424 // data members and cannot be applied to names declared const or static,
425 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000426 switch (DS.getStorageClassSpec()) {
427 case DeclSpec::SCS_unspecified:
428 case DeclSpec::SCS_typedef:
429 case DeclSpec::SCS_static:
430 // FALL THROUGH.
431 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000432 case DeclSpec::SCS_mutable:
433 if (isFunc) {
434 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000435 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000436 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000437 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
438
Sebastian Redla11f42f2008-11-17 23:24:37 +0000439 // FIXME: It would be nicer if the keyword was ignored only for this
440 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000441 D.getMutableDeclSpec().ClearStorageClassSpecs();
442 } else {
443 QualType T = GetTypeForDeclarator(D, S);
444 diag::kind err = static_cast<diag::kind>(0);
445 if (T->isReferenceType())
446 err = diag::err_mutable_reference;
447 else if (T.isConstQualified())
448 err = diag::err_mutable_const;
449 if (err != 0) {
450 if (DS.getStorageClassSpecLoc().isValid())
451 Diag(DS.getStorageClassSpecLoc(), err);
452 else
453 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000454 // FIXME: It would be nicer if the keyword was ignored only for this
455 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000456 D.getMutableDeclSpec().ClearStorageClassSpecs();
457 }
458 }
459 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000460 default:
461 if (DS.getStorageClassSpecLoc().isValid())
462 Diag(DS.getStorageClassSpecLoc(),
463 diag::err_storageclass_invalid_for_member);
464 else
465 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
466 D.getMutableDeclSpec().ClearStorageClassSpecs();
467 }
468
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000469 if (!isFunc &&
470 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
471 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000472 // Check also for this case:
473 //
474 // typedef int f();
475 // f a;
476 //
477 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
478 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
479 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000480
Sebastian Redl669d5d72008-11-14 23:42:31 +0000481 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
482 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000483 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000484
485 Decl *Member;
486 bool InvalidDecl = false;
487
488 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000489 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
490 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000491 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000492 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000493
494 if (!Member) return LastInGroup;
495
Douglas Gregor10bd3682008-11-17 22:58:34 +0000496 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000497
498 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
499 // specific methods. Use a wrapper class that can be used with all C++ class
500 // member decls.
501 CXXClassMemberWrapper(Member).setAccess(AS);
502
Douglas Gregor64bffa92008-11-05 16:20:31 +0000503 // C++ [dcl.init.aggr]p1:
504 // An aggregate is an array or a class (clause 9) with [...] no
505 // private or protected non-static data members (clause 11).
506 if (isInstField && (AS == AS_private || AS == AS_protected))
507 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
508
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000509 if (DS.isVirtualSpecified()) {
510 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
511 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
512 InvalidDecl = true;
513 } else {
514 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
515 CurClass->setAggregate(false);
516 CurClass->setPolymorphic(true);
517 }
518 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000519
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000520 if (BitWidth) {
521 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
522 // constant-expression be a value equal to zero.
523 // FIXME: Check this.
524
525 if (D.isFunctionDeclarator()) {
526 // FIXME: Emit diagnostic about only constructors taking base initializers
527 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000528 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000529 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000530 InvalidDecl = true;
531
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000532 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000533 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000534 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000535 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000536 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000537 InvalidDecl = true;
538 }
539
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000540 } else if (isa<FunctionDecl>(Member)) {
541 // A function typedef ("typedef int f(); f a;").
542 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000543 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000544 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000545 InvalidDecl = true;
546
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000547 } else if (isa<TypedefDecl>(Member)) {
548 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000549 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000550 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000551 InvalidDecl = true;
552
553 } else {
554 assert(isa<CXXClassVarDecl>(Member) &&
555 "Didn't we cover all member kinds?");
556 // C++ 9.6p3: A bit-field shall not be a static member.
557 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000558 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000559 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560 InvalidDecl = true;
561 }
562 }
563
564 if (Init) {
565 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
566 // if it declares a static member of const integral or const enumeration
567 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000568 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
569 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000570 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000571 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000572 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
573 CVD->getType()->isIntegralType()) {
574 // constant-initializer
575 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000576 InvalidDecl = true;
577
578 } else {
579 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000580 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000581 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000582 InvalidDecl = true;
583 }
584
585 } else {
586 // not static member.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000587 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000588 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000589 InvalidDecl = true;
590 }
591 }
592
593 if (InvalidDecl)
594 Member->setInvalidDecl();
595
596 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000597 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000598 return LastInGroup;
599 }
600 return Member;
601}
602
Douglas Gregor7ad83902008-11-05 04:29:56 +0000603/// ActOnMemInitializer - Handle a C++ member initializer.
604Sema::MemInitResult
605Sema::ActOnMemInitializer(DeclTy *ConstructorD,
606 Scope *S,
607 IdentifierInfo *MemberOrBase,
608 SourceLocation IdLoc,
609 SourceLocation LParenLoc,
610 ExprTy **Args, unsigned NumArgs,
611 SourceLocation *CommaLocs,
612 SourceLocation RParenLoc) {
613 CXXConstructorDecl *Constructor
614 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
615 if (!Constructor) {
616 // The user wrote a constructor initializer on a function that is
617 // not a C++ constructor. Ignore the error for now, because we may
618 // have more member initializers coming; we'll diagnose it just
619 // once in ActOnMemInitializers.
620 return true;
621 }
622
623 CXXRecordDecl *ClassDecl = Constructor->getParent();
624
625 // C++ [class.base.init]p2:
626 // Names in a mem-initializer-id are looked up in the scope of the
627 // constructor’s class and, if not found in that scope, are looked
628 // up in the scope containing the constructor’s
629 // definition. [Note: if the constructor’s class contains a member
630 // with the same name as a direct or virtual base class of the
631 // class, a mem-initializer-id naming the member or base class and
632 // composed of a single identifier refers to the class member. A
633 // mem-initializer-id for the hidden base class may be specified
634 // using a qualified name. ]
635 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000636 FieldDecl *Member = 0;
637 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase);
638 if (Result.first != Result.second)
639 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000640
641 // FIXME: Handle members of an anonymous union.
642
643 if (Member) {
644 // FIXME: Perform direct initialization of the member.
645 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
646 }
647
648 // It didn't name a member, so see if it names a class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000649 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000650 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000651 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
652 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000653
654 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
655 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000656 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000657 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000658
659 // C++ [class.base.init]p2:
660 // [...] Unless the mem-initializer-id names a nonstatic data
661 // member of the constructor’s class or a direct or virtual base
662 // of that class, the mem-initializer is ill-formed. A
663 // mem-initializer-list can initialize a base class using any
664 // name that denotes that base class type.
665
666 // First, check for a direct base class.
667 const CXXBaseSpecifier *DirectBaseSpec = 0;
668 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
669 Base != ClassDecl->bases_end(); ++Base) {
670 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
671 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
672 // We found a direct base of this type. That's what we're
673 // initializing.
674 DirectBaseSpec = &*Base;
675 break;
676 }
677 }
678
679 // Check for a virtual base class.
680 // FIXME: We might be able to short-circuit this if we know in
681 // advance that there are no virtual bases.
682 const CXXBaseSpecifier *VirtualBaseSpec = 0;
683 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
684 // We haven't found a base yet; search the class hierarchy for a
685 // virtual base class.
686 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
687 /*DetectVirtual=*/false);
688 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
689 for (BasePaths::paths_iterator Path = Paths.begin();
690 Path != Paths.end(); ++Path) {
691 if (Path->back().Base->isVirtual()) {
692 VirtualBaseSpec = Path->back().Base;
693 break;
694 }
695 }
696 }
697 }
698
699 // C++ [base.class.init]p2:
700 // If a mem-initializer-id is ambiguous because it designates both
701 // a direct non-virtual base class and an inherited virtual base
702 // class, the mem-initializer is ill-formed.
703 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000704 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
705 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000706
707 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
708}
709
710
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000711void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
712 DeclTy *TagDecl,
713 SourceLocation LBrac,
714 SourceLocation RBrac) {
715 ActOnFields(S, RLoc, TagDecl,
716 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000717 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000718}
719
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000720/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
721/// special functions, such as the default constructor, copy
722/// constructor, or destructor, to the given C++ class (C++
723/// [special]p1). This routine can only be executed just before the
724/// definition of the class is complete.
725void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000726 QualType ClassType = Context.getTypeDeclType(ClassDecl);
727 ClassType = Context.getCanonicalType(ClassType);
728
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000729 if (!ClassDecl->hasUserDeclaredConstructor()) {
730 // C++ [class.ctor]p5:
731 // A default constructor for a class X is a constructor of class X
732 // that can be called without an argument. If there is no
733 // user-declared constructor for class X, a default constructor is
734 // implicitly declared. An implicitly-declared default constructor
735 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000736 DeclarationName Name
737 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000738 CXXConstructorDecl *DefaultCon =
739 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000740 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000741 Context.getFunctionType(Context.VoidTy,
742 0, 0, false, 0),
743 /*isExplicit=*/false,
744 /*isInline=*/true,
745 /*isImplicitlyDeclared=*/true);
746 DefaultCon->setAccess(AS_public);
747 ClassDecl->addConstructor(Context, DefaultCon);
748 }
749
750 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
751 // C++ [class.copy]p4:
752 // If the class definition does not explicitly declare a copy
753 // constructor, one is declared implicitly.
754
755 // C++ [class.copy]p5:
756 // The implicitly-declared copy constructor for a class X will
757 // have the form
758 //
759 // X::X(const X&)
760 //
761 // if
762 bool HasConstCopyConstructor = true;
763
764 // -- each direct or virtual base class B of X has a copy
765 // constructor whose first parameter is of type const B& or
766 // const volatile B&, and
767 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
768 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
769 const CXXRecordDecl *BaseClassDecl
770 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
771 HasConstCopyConstructor
772 = BaseClassDecl->hasConstCopyConstructor(Context);
773 }
774
775 // -- for all the nonstatic data members of X that are of a
776 // class type M (or array thereof), each such class type
777 // has a copy constructor whose first parameter is of type
778 // const M& or const volatile M&.
779 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
780 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
781 QualType FieldType = (*Field)->getType();
782 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
783 FieldType = Array->getElementType();
784 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
785 const CXXRecordDecl *FieldClassDecl
786 = cast<CXXRecordDecl>(FieldClassType->getDecl());
787 HasConstCopyConstructor
788 = FieldClassDecl->hasConstCopyConstructor(Context);
789 }
790 }
791
792 // Otherwise, the implicitly declared copy constructor will have
793 // the form
794 //
795 // X::X(X&)
796 QualType ArgType = Context.getTypeDeclType(ClassDecl);
797 if (HasConstCopyConstructor)
798 ArgType = ArgType.withConst();
799 ArgType = Context.getReferenceType(ArgType);
800
801 // An implicitly-declared copy constructor is an inline public
802 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000803 DeclarationName Name
804 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000805 CXXConstructorDecl *CopyConstructor
806 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000807 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000808 Context.getFunctionType(Context.VoidTy,
809 &ArgType, 1,
810 false, 0),
811 /*isExplicit=*/false,
812 /*isInline=*/true,
813 /*isImplicitlyDeclared=*/true);
814 CopyConstructor->setAccess(AS_public);
815
816 // Add the parameter to the constructor.
817 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
818 ClassDecl->getLocation(),
819 /*IdentifierInfo=*/0,
820 ArgType, VarDecl::None, 0, 0);
821 CopyConstructor->setParams(&FromParam, 1);
822
823 ClassDecl->addConstructor(Context, CopyConstructor);
824 }
825
Douglas Gregor42a552f2008-11-05 20:51:48 +0000826 if (!ClassDecl->getDestructor()) {
827 // C++ [class.dtor]p2:
828 // If a class has no user-declared destructor, a destructor is
829 // declared implicitly. An implicitly-declared destructor is an
830 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000831 DeclarationName Name
832 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000833 CXXDestructorDecl *Destructor
834 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000835 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000836 Context.getFunctionType(Context.VoidTy,
837 0, 0, false, 0),
838 /*isInline=*/true,
839 /*isImplicitlyDeclared=*/true);
840 Destructor->setAccess(AS_public);
841 ClassDecl->setDestructor(Destructor);
842 }
843
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000844 // FIXME: Implicit copy assignment operator
845}
846
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000847void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000848 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000849 FieldCollector->FinishClass();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000850 AddImplicitlyDeclaredMembersToClass(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000851 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000852
853 // Everything, including inline method definitions, have been parsed.
854 // Let the consumer know of the new TagDecl definition.
855 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000856}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000857
Douglas Gregor42a552f2008-11-05 20:51:48 +0000858/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
859/// the well-formednes of the constructor declarator @p D with type @p
860/// R. If there are any errors in the declarator, this routine will
861/// emit diagnostics and return true. Otherwise, it will return
862/// false. Either way, the type @p R will be updated to reflect a
863/// well-formed type for the constructor.
864bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
865 FunctionDecl::StorageClass& SC) {
866 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
867 bool isInvalid = false;
868
869 // C++ [class.ctor]p3:
870 // A constructor shall not be virtual (10.3) or static (9.4). A
871 // constructor can be invoked for a const, volatile or const
872 // volatile object. A constructor shall not be declared const,
873 // volatile, or const volatile (9.3.2).
874 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000875 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
876 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
877 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000878 isInvalid = true;
879 }
880 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000881 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
882 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
883 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000884 isInvalid = true;
885 SC = FunctionDecl::None;
886 }
887 if (D.getDeclSpec().hasTypeSpecifier()) {
888 // Constructors don't have return types, but the parser will
889 // happily parse something like:
890 //
891 // class X {
892 // float X(float);
893 // };
894 //
895 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000896 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
897 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
898 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000899 }
900 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
901 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
902 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000903 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
904 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000905 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000906 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
907 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000908 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000909 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
910 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000911 }
912
913 // Rebuild the function type "R" without any type qualifiers (in
914 // case any of the errors above fired) and with "void" as the
915 // return type, since constructors don't have return types. We
916 // *always* have to do this, because GetTypeForDeclarator will
917 // put in a result type of "int" when none was specified.
918 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
919 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
920 Proto->getNumArgs(),
921 Proto->isVariadic(),
922 0);
923
924 return isInvalid;
925}
926
927/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
928/// the well-formednes of the destructor declarator @p D with type @p
929/// R. If there are any errors in the declarator, this routine will
930/// emit diagnostics and return true. Otherwise, it will return
931/// false. Either way, the type @p R will be updated to reflect a
932/// well-formed type for the destructor.
933bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
934 FunctionDecl::StorageClass& SC) {
935 bool isInvalid = false;
936
937 // C++ [class.dtor]p1:
938 // [...] A typedef-name that names a class is a class-name
939 // (7.1.3); however, a typedef-name that names a class shall not
940 // be used as the identifier in the declarator for a destructor
941 // declaration.
942 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
943 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000944 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000945 << TypedefD->getDeclName();
Douglas Gregor55c60952008-11-10 14:41:22 +0000946 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000947 }
948
949 // C++ [class.dtor]p2:
950 // A destructor is used to destroy objects of its class type. A
951 // destructor takes no parameters, and no return type can be
952 // specified for it (not even void). The address of a destructor
953 // shall not be taken. A destructor shall not be static. A
954 // destructor can be invoked for a const, volatile or const
955 // volatile object. A destructor shall not be declared const,
956 // volatile or const volatile (9.3.2).
957 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000958 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
959 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
960 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000961 isInvalid = true;
962 SC = FunctionDecl::None;
963 }
964 if (D.getDeclSpec().hasTypeSpecifier()) {
965 // Destructors don't have return types, but the parser will
966 // happily parse something like:
967 //
968 // class X {
969 // float ~X();
970 // };
971 //
972 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000973 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
974 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
975 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000976 }
977 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
978 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
979 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
981 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000982 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
984 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000985 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
987 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000988 }
989
990 // Make sure we don't have any parameters.
991 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
992 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
993
994 // Delete the parameters.
995 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
996 if (FTI.NumArgs) {
997 delete [] FTI.ArgInfo;
998 FTI.NumArgs = 0;
999 FTI.ArgInfo = 0;
1000 }
1001 }
1002
1003 // Make sure the destructor isn't variadic.
1004 if (R->getAsFunctionTypeProto()->isVariadic())
1005 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1006
1007 // Rebuild the function type "R" without any type qualifiers or
1008 // parameters (in case any of the errors above fired) and with
1009 // "void" as the return type, since destructors don't have return
1010 // types. We *always* have to do this, because GetTypeForDeclarator
1011 // will put in a result type of "int" when none was specified.
1012 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1013
1014 return isInvalid;
1015}
1016
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001017/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1018/// well-formednes of the conversion function declarator @p D with
1019/// type @p R. If there are any errors in the declarator, this routine
1020/// will emit diagnostics and return true. Otherwise, it will return
1021/// false. Either way, the type @p R will be updated to reflect a
1022/// well-formed type for the conversion operator.
1023bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1024 FunctionDecl::StorageClass& SC) {
1025 bool isInvalid = false;
1026
1027 // C++ [class.conv.fct]p1:
1028 // Neither parameter types nor return type can be specified. The
1029 // type of a conversion function (8.3.5) is “function taking no
1030 // parameter returning conversion-type-id.”
1031 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001032 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1033 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1034 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001035 isInvalid = true;
1036 SC = FunctionDecl::None;
1037 }
1038 if (D.getDeclSpec().hasTypeSpecifier()) {
1039 // Conversion functions don't have return types, but the parser will
1040 // happily parse something like:
1041 //
1042 // class X {
1043 // float operator bool();
1044 // };
1045 //
1046 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001047 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1048 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1049 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001050 }
1051
1052 // Make sure we don't have any parameters.
1053 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1054 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1055
1056 // Delete the parameters.
1057 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1058 if (FTI.NumArgs) {
1059 delete [] FTI.ArgInfo;
1060 FTI.NumArgs = 0;
1061 FTI.ArgInfo = 0;
1062 }
1063 }
1064
1065 // Make sure the conversion function isn't variadic.
1066 if (R->getAsFunctionTypeProto()->isVariadic())
1067 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1068
1069 // C++ [class.conv.fct]p4:
1070 // The conversion-type-id shall not represent a function type nor
1071 // an array type.
1072 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1073 if (ConvType->isArrayType()) {
1074 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1075 ConvType = Context.getPointerType(ConvType);
1076 } else if (ConvType->isFunctionType()) {
1077 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1078 ConvType = Context.getPointerType(ConvType);
1079 }
1080
1081 // Rebuild the function type "R" without any parameters (in case any
1082 // of the errors above fired) and with the conversion type as the
1083 // return type.
1084 R = Context.getFunctionType(ConvType, 0, 0, false,
1085 R->getAsFunctionTypeProto()->getTypeQuals());
1086
1087 return isInvalid;
1088}
1089
Douglas Gregorb48fe382008-10-31 09:07:45 +00001090/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1091/// the declaration of the given C++ constructor ConDecl that was
1092/// built from declarator D. This routine is responsible for checking
1093/// that the newly-created constructor declaration is well-formed and
1094/// for recording it in the C++ class. Example:
1095///
1096/// @code
1097/// class X {
1098/// X(); // X::X() will be the ConDecl.
1099/// };
1100/// @endcode
1101Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1102 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregor60d62c22008-10-31 16:23:19 +00001103
1104 // Check default arguments on the constructor
1105 CheckCXXDefaultArguments(ConDecl);
1106
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001107 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1108 if (!ClassDecl) {
1109 ConDecl->setInvalidDecl();
1110 return ConDecl;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001111 }
1112
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001113 // Make sure this constructor is an overload of the existing
1114 // constructors.
1115 OverloadedFunctionDecl::function_iterator MatchedDecl;
1116 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001117 Diag(ConDecl->getLocation(), diag::err_constructor_redeclared)
1118 << SourceRange(ConDecl->getLocation());
Chris Lattner5f4a6822008-11-23 23:12:31 +00001119 Diag((*MatchedDecl)->getLocation(), diag::note_previous_declaration)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001120 << SourceRange((*MatchedDecl)->getLocation());
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001121 ConDecl->setInvalidDecl();
1122 return ConDecl;
1123 }
1124
1125
1126 // C++ [class.copy]p3:
1127 // A declaration of a constructor for a class X is ill-formed if
1128 // its first parameter is of type (optionally cv-qualified) X and
1129 // either there are no other parameters or else all other
1130 // parameters have default arguments.
1131 if ((ConDecl->getNumParams() == 1) ||
1132 (ConDecl->getNumParams() > 1 &&
1133 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1134 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1135 QualType ClassTy = Context.getTagDeclType(
1136 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1137 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001138 Diag(ConDecl->getLocation(), diag::err_constructor_byvalue_arg)
1139 << SourceRange(ConDecl->getParamDecl(0)->getLocation());
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001140 ConDecl->setInvalidDecl();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001141 return ConDecl;
Douglas Gregor030ff0c2008-10-31 20:25:05 +00001142 }
1143 }
1144
1145 // Add this constructor to the set of constructors of the current
1146 // class.
1147 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001148 return (DeclTy *)ConDecl;
1149}
1150
Douglas Gregor42a552f2008-11-05 20:51:48 +00001151/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1152/// the declaration of the given C++ @p Destructor. This routine is
1153/// responsible for recording the destructor in the C++ class, if
1154/// possible.
1155Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1156 assert(Destructor && "Expected to receive a destructor declaration");
1157
1158 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1159
1160 // Make sure we aren't redeclaring the destructor.
1161 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1162 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1163 Diag(PrevDestructor->getLocation(),
Chris Lattner5f4a6822008-11-23 23:12:31 +00001164 PrevDestructor->isThisDeclarationADefinition() ?
1165 diag::note_previous_definition
1166 : diag::note_previous_declaration);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001167 Destructor->setInvalidDecl();
1168 return Destructor;
1169 }
1170
1171 ClassDecl->setDestructor(Destructor);
1172 return (DeclTy *)Destructor;
1173}
1174
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001175/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1176/// the declaration of the given C++ conversion function. This routine
1177/// is responsible for recording the conversion function in the C++
1178/// class, if possible.
1179Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1180 assert(Conversion && "Expected to receive a conversion function declaration");
1181
1182 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1183
1184 // Make sure we aren't redeclaring the conversion function.
1185 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1186 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1187 for (OverloadedFunctionDecl::function_iterator Func
1188 = Conversions->function_begin();
1189 Func != Conversions->function_end(); ++Func) {
1190 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1191 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1192 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1193 Diag(OtherConv->getLocation(),
1194 OtherConv->isThisDeclarationADefinition()?
Chris Lattner5f4a6822008-11-23 23:12:31 +00001195 diag::note_previous_definition
1196 : diag::note_previous_declaration);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001197 Conversion->setInvalidDecl();
1198 return (DeclTy *)Conversion;
1199 }
1200 }
1201
1202 // C++ [class.conv.fct]p1:
1203 // [...] A conversion function is never used to convert a
1204 // (possibly cv-qualified) object to the (possibly cv-qualified)
1205 // same object type (or a reference to it), to a (possibly
1206 // cv-qualified) base class of that type (or a reference to it),
1207 // or to (possibly cv-qualified) void.
1208 // FIXME: Suppress this warning if the conversion function ends up
1209 // being a virtual function that overrides a virtual function in a
1210 // base class.
1211 QualType ClassType
1212 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1213 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1214 ConvType = ConvTypeRef->getPointeeType();
1215 if (ConvType->isRecordType()) {
1216 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1217 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001218 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001219 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001220 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001221 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001222 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001223 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001224 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001225 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001226 }
1227
1228 ClassDecl->addConversionFunction(Context, Conversion);
1229
1230 return (DeclTy *)Conversion;
1231}
1232
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001233//===----------------------------------------------------------------------===//
1234// Namespace Handling
1235//===----------------------------------------------------------------------===//
1236
1237/// ActOnStartNamespaceDef - This is called at the start of a namespace
1238/// definition.
1239Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1240 SourceLocation IdentLoc,
1241 IdentifierInfo *II,
1242 SourceLocation LBrace) {
1243 NamespaceDecl *Namespc =
1244 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1245 Namespc->setLBracLoc(LBrace);
1246
1247 Scope *DeclRegionScope = NamespcScope->getParent();
1248
1249 if (II) {
1250 // C++ [namespace.def]p2:
1251 // The identifier in an original-namespace-definition shall not have been
1252 // previously defined in the declarative region in which the
1253 // original-namespace-definition appears. The identifier in an
1254 // original-namespace-definition is the name of the namespace. Subsequently
1255 // in that declarative region, it is treated as an original-namespace-name.
1256
1257 Decl *PrevDecl =
Douglas Gregor44b43212008-12-11 16:49:14 +00001258 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1259 /*enableLazyBuiltinCreation=*/false,
1260 /*LookupInParent=*/false);
1261
1262 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1263 // This is an extended namespace definition.
1264 // Attach this namespace decl to the chain of extended namespace
1265 // definitions.
1266 OrigNS->setNextNamespace(Namespc);
1267 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001268
Douglas Gregor44b43212008-12-11 16:49:14 +00001269 // Remove the previous declaration from the scope.
1270 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001271 IdResolver.RemoveDecl(OrigNS);
1272 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001273 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001274 } else if (PrevDecl) {
1275 // This is an invalid name redefinition.
1276 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1277 << Namespc->getDeclName();
1278 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1279 Namespc->setInvalidDecl();
1280 // Continue on to push Namespc as current DeclContext and return it.
1281 }
1282
1283 PushOnScopeChains(Namespc, DeclRegionScope);
1284 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001285 // FIXME: Handle anonymous namespaces
1286 }
1287
1288 // Although we could have an invalid decl (i.e. the namespace name is a
1289 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001290 // FIXME: We should be able to push Namespc here, so that the
1291 // each DeclContext for the namespace has the declarations
1292 // that showed up in that particular namespace definition.
1293 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001294 return Namespc;
1295}
1296
1297/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1298/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1299void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1300 Decl *Dcl = static_cast<Decl *>(D);
1301 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1302 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1303 Namespc->setRBracLoc(RBrace);
1304 PopDeclContext();
1305}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001306
1307
1308/// AddCXXDirectInitializerToDecl - This action is called immediately after
1309/// ActOnDeclarator, when a C++ direct initializer is present.
1310/// e.g: "int x(1);"
1311void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1312 ExprTy **ExprTys, unsigned NumExprs,
1313 SourceLocation *CommaLocs,
1314 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001315 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001316 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001317
1318 // If there is no declaration, there was an error parsing it. Just ignore
1319 // the initializer.
1320 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001321 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001322 delete static_cast<Expr *>(ExprTys[i]);
1323 return;
1324 }
1325
1326 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1327 if (!VDecl) {
1328 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1329 RealDecl->setInvalidDecl();
1330 return;
1331 }
1332
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001333 // We will treat direct-initialization as a copy-initialization:
1334 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001335 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1336 //
1337 // Clients that want to distinguish between the two forms, can check for
1338 // direct initializer using VarDecl::hasCXXDirectInitializer().
1339 // A major benefit is that clients that don't particularly care about which
1340 // exactly form was it (like the CodeGen) can handle both cases without
1341 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001342
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001343 // C++ 8.5p11:
1344 // The form of initialization (using parentheses or '=') is generally
1345 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001346 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001347 QualType DeclInitType = VDecl->getType();
1348 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1349 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001350
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001351 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001352 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001353 = PerformInitializationByConstructor(DeclInitType,
1354 (Expr **)ExprTys, NumExprs,
1355 VDecl->getLocation(),
1356 SourceRange(VDecl->getLocation(),
1357 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001358 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001359 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001360 if (!Constructor) {
1361 RealDecl->setInvalidDecl();
1362 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001363
1364 // Let clients know that initialization was done with a direct
1365 // initializer.
1366 VDecl->setCXXDirectInitializer(true);
1367
1368 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1369 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001370 return;
1371 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001372
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001373 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001374 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1375 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001376 RealDecl->setInvalidDecl();
1377 return;
1378 }
1379
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001380 // Let clients know that initialization was done with a direct initializer.
1381 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001382
1383 assert(NumExprs == 1 && "Expected 1 expression");
1384 // Set the init expression, handles conversions.
1385 AddInitializerToDecl(Dcl, ExprTys[0]);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001386}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001387
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001388/// PerformInitializationByConstructor - Perform initialization by
1389/// constructor (C++ [dcl.init]p14), which may occur as part of
1390/// direct-initialization or copy-initialization. We are initializing
1391/// an object of type @p ClassType with the given arguments @p
1392/// Args. @p Loc is the location in the source code where the
1393/// initializer occurs (e.g., a declaration, member initializer,
1394/// functional cast, etc.) while @p Range covers the whole
1395/// initialization. @p InitEntity is the entity being initialized,
1396/// which may by the name of a declaration or a type. @p Kind is the
1397/// kind of initialization we're performing, which affects whether
1398/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001399/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001400/// when the initialization fails, emits a diagnostic and returns
1401/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001402CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001403Sema::PerformInitializationByConstructor(QualType ClassType,
1404 Expr **Args, unsigned NumArgs,
1405 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001406 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001407 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001408 const RecordType *ClassRec = ClassType->getAsRecordType();
1409 assert(ClassRec && "Can only initialize a class type here");
1410
1411 // C++ [dcl.init]p14:
1412 //
1413 // If the initialization is direct-initialization, or if it is
1414 // copy-initialization where the cv-unqualified version of the
1415 // source type is the same class as, or a derived class of, the
1416 // class of the destination, constructors are considered. The
1417 // applicable constructors are enumerated (13.3.1.3), and the
1418 // best one is chosen through overload resolution (13.3). The
1419 // constructor so selected is called to initialize the object,
1420 // with the initializer expression(s) as its argument(s). If no
1421 // constructor applies, or the overload resolution is ambiguous,
1422 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001423 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1424 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001425
1426 // Add constructors to the overload set.
1427 OverloadedFunctionDecl *Constructors
1428 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1429 for (OverloadedFunctionDecl::function_iterator Con
1430 = Constructors->function_begin();
1431 Con != Constructors->function_end(); ++Con) {
1432 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1433 if ((Kind == IK_Direct) ||
1434 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1435 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1436 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1437 }
1438
Douglas Gregor18fe5682008-11-03 20:45:27 +00001439 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001440 switch (BestViableFunction(CandidateSet, Best)) {
1441 case OR_Success:
1442 // We found a constructor. Return it.
1443 return cast<CXXConstructorDecl>(Best->Function);
1444
1445 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001446 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1447 << InitEntity << (unsigned)CandidateSet.size() << Range;
1448 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001449 return 0;
1450
1451 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001452 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001453 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1454 return 0;
1455 }
1456
1457 return 0;
1458}
1459
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001460/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1461/// determine whether they are reference-related,
1462/// reference-compatible, reference-compatible with added
1463/// qualification, or incompatible, for use in C++ initialization by
1464/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1465/// type, and the first type (T1) is the pointee type of the reference
1466/// type being initialized.
1467Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001468Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1469 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001470 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1471 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1472
1473 T1 = Context.getCanonicalType(T1);
1474 T2 = Context.getCanonicalType(T2);
1475 QualType UnqualT1 = T1.getUnqualifiedType();
1476 QualType UnqualT2 = T2.getUnqualifiedType();
1477
1478 // C++ [dcl.init.ref]p4:
1479 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1480 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1481 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001482 if (UnqualT1 == UnqualT2)
1483 DerivedToBase = false;
1484 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1485 DerivedToBase = true;
1486 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001487 return Ref_Incompatible;
1488
1489 // At this point, we know that T1 and T2 are reference-related (at
1490 // least).
1491
1492 // C++ [dcl.init.ref]p4:
1493 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1494 // reference-related to T2 and cv1 is the same cv-qualification
1495 // as, or greater cv-qualification than, cv2. For purposes of
1496 // overload resolution, cases for which cv1 is greater
1497 // cv-qualification than cv2 are identified as
1498 // reference-compatible with added qualification (see 13.3.3.2).
1499 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1500 return Ref_Compatible;
1501 else if (T1.isMoreQualifiedThan(T2))
1502 return Ref_Compatible_With_Added_Qualification;
1503 else
1504 return Ref_Related;
1505}
1506
1507/// CheckReferenceInit - Check the initialization of a reference
1508/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1509/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001510/// list), and DeclType is the type of the declaration. When ICS is
1511/// non-null, this routine will compute the implicit conversion
1512/// sequence according to C++ [over.ics.ref] and will not produce any
1513/// diagnostics; when ICS is null, it will emit diagnostics when any
1514/// errors are found. Either way, a return value of true indicates
1515/// that there was a failure, a return value of false indicates that
1516/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001517///
1518/// When @p SuppressUserConversions, user-defined conversions are
1519/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001520bool
1521Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001522 ImplicitConversionSequence *ICS,
1523 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001524 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1525
1526 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1527 QualType T2 = Init->getType();
1528
Douglas Gregor904eed32008-11-10 20:40:00 +00001529 // If the initializer is the address of an overloaded function, try
1530 // to resolve the overloaded function. If all goes well, T2 is the
1531 // type of the resulting function.
1532 if (T2->isOverloadType()) {
1533 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1534 ICS != 0);
1535 if (Fn) {
1536 // Since we're performing this reference-initialization for
1537 // real, update the initializer with the resulting function.
1538 if (!ICS)
1539 FixOverloadedFunctionReference(Init, Fn);
1540
1541 T2 = Fn->getType();
1542 }
1543 }
1544
Douglas Gregor15da57e2008-10-29 02:00:59 +00001545 // Compute some basic properties of the types and the initializer.
1546 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001547 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001548 ReferenceCompareResult RefRelationship
1549 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1550
1551 // Most paths end in a failed conversion.
1552 if (ICS)
1553 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001554
1555 // C++ [dcl.init.ref]p5:
1556 // A reference to type “cv1 T1” is initialized by an expression
1557 // of type “cv2 T2” as follows:
1558
1559 // -- If the initializer expression
1560
1561 bool BindsDirectly = false;
1562 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1563 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001564 //
1565 // Note that the bit-field check is skipped if we are just computing
1566 // the implicit conversion sequence (C++ [over.best.ics]p2).
1567 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1568 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001569 BindsDirectly = true;
1570
Douglas Gregor15da57e2008-10-29 02:00:59 +00001571 if (ICS) {
1572 // C++ [over.ics.ref]p1:
1573 // When a parameter of reference type binds directly (8.5.3)
1574 // to an argument expression, the implicit conversion sequence
1575 // is the identity conversion, unless the argument expression
1576 // has a type that is a derived class of the parameter type,
1577 // in which case the implicit conversion sequence is a
1578 // derived-to-base Conversion (13.3.3.1).
1579 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1580 ICS->Standard.First = ICK_Identity;
1581 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1582 ICS->Standard.Third = ICK_Identity;
1583 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1584 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001585 ICS->Standard.ReferenceBinding = true;
1586 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001587
1588 // Nothing more to do: the inaccessibility/ambiguity check for
1589 // derived-to-base conversions is suppressed when we're
1590 // computing the implicit conversion sequence (C++
1591 // [over.best.ics]p2).
1592 return false;
1593 } else {
1594 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001595 // FIXME: Binding to a subobject of the lvalue is going to require
1596 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001597 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001598 }
1599 }
1600
1601 // -- has a class type (i.e., T2 is a class type) and can be
1602 // implicitly converted to an lvalue of type “cv3 T3,”
1603 // where “cv1 T1” is reference-compatible with “cv3 T3”
1604 // 92) (this conversion is selected by enumerating the
1605 // applicable conversion functions (13.3.1.6) and choosing
1606 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001607 if (!SuppressUserConversions && T2->isRecordType()) {
1608 // FIXME: Look for conversions in base classes!
1609 CXXRecordDecl *T2RecordDecl
1610 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001611
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001612 OverloadCandidateSet CandidateSet;
1613 OverloadedFunctionDecl *Conversions
1614 = T2RecordDecl->getConversionFunctions();
1615 for (OverloadedFunctionDecl::function_iterator Func
1616 = Conversions->function_begin();
1617 Func != Conversions->function_end(); ++Func) {
1618 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1619
1620 // If the conversion function doesn't return a reference type,
1621 // it can't be considered for this conversion.
1622 // FIXME: This will change when we support rvalue references.
1623 if (Conv->getConversionType()->isReferenceType())
1624 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1625 }
1626
1627 OverloadCandidateSet::iterator Best;
1628 switch (BestViableFunction(CandidateSet, Best)) {
1629 case OR_Success:
1630 // This is a direct binding.
1631 BindsDirectly = true;
1632
1633 if (ICS) {
1634 // C++ [over.ics.ref]p1:
1635 //
1636 // [...] If the parameter binds directly to the result of
1637 // applying a conversion function to the argument
1638 // expression, the implicit conversion sequence is a
1639 // user-defined conversion sequence (13.3.3.1.2), with the
1640 // second standard conversion sequence either an identity
1641 // conversion or, if the conversion function returns an
1642 // entity of a type that is a derived class of the parameter
1643 // type, a derived-to-base Conversion.
1644 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1645 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1646 ICS->UserDefined.After = Best->FinalConversion;
1647 ICS->UserDefined.ConversionFunction = Best->Function;
1648 assert(ICS->UserDefined.After.ReferenceBinding &&
1649 ICS->UserDefined.After.DirectBinding &&
1650 "Expected a direct reference binding!");
1651 return false;
1652 } else {
1653 // Perform the conversion.
1654 // FIXME: Binding to a subobject of the lvalue is going to require
1655 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001656 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001657 }
1658 break;
1659
1660 case OR_Ambiguous:
1661 assert(false && "Ambiguous reference binding conversions not implemented.");
1662 return true;
1663
1664 case OR_No_Viable_Function:
1665 // There was no suitable conversion; continue with other checks.
1666 break;
1667 }
1668 }
1669
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001670 if (BindsDirectly) {
1671 // C++ [dcl.init.ref]p4:
1672 // [...] In all cases where the reference-related or
1673 // reference-compatible relationship of two types is used to
1674 // establish the validity of a reference binding, and T1 is a
1675 // base class of T2, a program that necessitates such a binding
1676 // is ill-formed if T1 is an inaccessible (clause 11) or
1677 // ambiguous (10.2) base class of T2.
1678 //
1679 // Note that we only check this condition when we're allowed to
1680 // complain about errors, because we should not be checking for
1681 // ambiguity (or inaccessibility) unless the reference binding
1682 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001683 if (DerivedToBase)
1684 return CheckDerivedToBaseConversion(T2, T1,
1685 Init->getSourceRange().getBegin(),
1686 Init->getSourceRange());
1687 else
1688 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001689 }
1690
1691 // -- Otherwise, the reference shall be to a non-volatile const
1692 // type (i.e., cv1 shall be const).
1693 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001694 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001695 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001696 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001697 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1698 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001699 return true;
1700 }
1701
1702 // -- If the initializer expression is an rvalue, with T2 a
1703 // class type, and “cv1 T1” is reference-compatible with
1704 // “cv2 T2,” the reference is bound in one of the
1705 // following ways (the choice is implementation-defined):
1706 //
1707 // -- The reference is bound to the object represented by
1708 // the rvalue (see 3.10) or to a sub-object within that
1709 // object.
1710 //
1711 // -- A temporary of type “cv1 T2” [sic] is created, and
1712 // a constructor is called to copy the entire rvalue
1713 // object into the temporary. The reference is bound to
1714 // the temporary or to a sub-object within the
1715 // temporary.
1716 //
1717 //
1718 // The constructor that would be used to make the copy
1719 // shall be callable whether or not the copy is actually
1720 // done.
1721 //
1722 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1723 // freedom, so we will always take the first option and never build
1724 // a temporary in this case. FIXME: We will, however, have to check
1725 // for the presence of a copy constructor in C++98/03 mode.
1726 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001727 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1728 if (ICS) {
1729 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1730 ICS->Standard.First = ICK_Identity;
1731 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1732 ICS->Standard.Third = ICK_Identity;
1733 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1734 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001735 ICS->Standard.ReferenceBinding = true;
1736 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001737 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001738 // FIXME: Binding to a subobject of the rvalue is going to require
1739 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001740 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001741 }
1742 return false;
1743 }
1744
1745 // -- Otherwise, a temporary of type “cv1 T1” is created and
1746 // initialized from the initializer expression using the
1747 // rules for a non-reference copy initialization (8.5). The
1748 // reference is then bound to the temporary. If T1 is
1749 // reference-related to T2, cv1 must be the same
1750 // cv-qualification as, or greater cv-qualification than,
1751 // cv2; otherwise, the program is ill-formed.
1752 if (RefRelationship == Ref_Related) {
1753 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1754 // we would be reference-compatible or reference-compatible with
1755 // added qualification. But that wasn't the case, so the reference
1756 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001757 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001758 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001759 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001760 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1761 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001762 return true;
1763 }
1764
1765 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001766 if (ICS) {
1767 /// C++ [over.ics.ref]p2:
1768 ///
1769 /// When a parameter of reference type is not bound directly to
1770 /// an argument expression, the conversion sequence is the one
1771 /// required to convert the argument expression to the
1772 /// underlying type of the reference according to
1773 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1774 /// to copy-initializing a temporary of the underlying type with
1775 /// the argument expression. Any difference in top-level
1776 /// cv-qualification is subsumed by the initialization itself
1777 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001778 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001779 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1780 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001781 return PerformImplicitConversion(Init, T1);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001782 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001783}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001784
1785/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1786/// of this overloaded operator is well-formed. If so, returns false;
1787/// otherwise, emits appropriate diagnostics and returns true.
1788bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001789 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001790 "Expected an overloaded operator declaration");
1791
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001792 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1793
1794 // C++ [over.oper]p5:
1795 // The allocation and deallocation functions, operator new,
1796 // operator new[], operator delete and operator delete[], are
1797 // described completely in 3.7.3. The attributes and restrictions
1798 // found in the rest of this subclause do not apply to them unless
1799 // explicitly stated in 3.7.3.
1800 // FIXME: Write a separate routine for checking this. For now, just
1801 // allow it.
1802 if (Op == OO_New || Op == OO_Array_New ||
1803 Op == OO_Delete || Op == OO_Array_Delete)
1804 return false;
1805
1806 // C++ [over.oper]p6:
1807 // An operator function shall either be a non-static member
1808 // function or be a non-member function and have at least one
1809 // parameter whose type is a class, a reference to a class, an
1810 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001811 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1812 if (MethodDecl->isStatic())
1813 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001814 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001815 } else {
1816 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001817 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1818 ParamEnd = FnDecl->param_end();
1819 Param != ParamEnd; ++Param) {
1820 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001821 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1822 ClassOrEnumParam = true;
1823 break;
1824 }
1825 }
1826
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001827 if (!ClassOrEnumParam)
1828 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001829 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001830 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001831 }
1832
1833 // C++ [over.oper]p8:
1834 // An operator function cannot have default arguments (8.3.6),
1835 // except where explicitly stated below.
1836 //
1837 // Only the function-call operator allows default arguments
1838 // (C++ [over.call]p1).
1839 if (Op != OO_Call) {
1840 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1841 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001842 if (Expr *DefArg = (*Param)->getDefaultArg())
1843 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001844 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001845 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001846 }
1847 }
1848
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001849 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1850 { false, false, false }
1851#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1852 , { Unary, Binary, MemberOnly }
1853#include "clang/Basic/OperatorKinds.def"
1854 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001855
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001856 bool CanBeUnaryOperator = OperatorUses[Op][0];
1857 bool CanBeBinaryOperator = OperatorUses[Op][1];
1858 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001859
1860 // C++ [over.oper]p8:
1861 // [...] Operator functions cannot have more or fewer parameters
1862 // than the number required for the corresponding operator, as
1863 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001864 unsigned NumParams = FnDecl->getNumParams()
1865 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001866 if (Op != OO_Call &&
1867 ((NumParams == 1 && !CanBeUnaryOperator) ||
1868 (NumParams == 2 && !CanBeBinaryOperator) ||
1869 (NumParams < 1) || (NumParams > 2))) {
1870 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00001871 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001872 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001873 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001874 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001875 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001876 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001877 assert(CanBeBinaryOperator &&
1878 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00001879 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001880 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001881
Chris Lattner416e46f2008-11-21 07:57:12 +00001882 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001883 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001884 }
1885
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001886 // Overloaded operators other than operator() cannot be variadic.
1887 if (Op != OO_Call &&
1888 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001889 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001890 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001891 }
1892
1893 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001894 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1895 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001896 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001897 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001898 }
1899
1900 // C++ [over.inc]p1:
1901 // The user-defined function called operator++ implements the
1902 // prefix and postfix ++ operator. If this function is a member
1903 // function with no parameters, or a non-member function with one
1904 // parameter of class or enumeration type, it defines the prefix
1905 // increment operator ++ for objects of that type. If the function
1906 // is a member function with one parameter (which shall be of type
1907 // int) or a non-member function with two parameters (the second
1908 // of which shall be of type int), it defines the postfix
1909 // increment operator ++ for objects of that type.
1910 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1911 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1912 bool ParamIsInt = false;
1913 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1914 ParamIsInt = BT->getKind() == BuiltinType::Int;
1915
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001916 if (!ParamIsInt)
1917 return Diag(LastParam->getLocation(),
1918 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00001919 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001920 }
1921
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001922 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001923}