blob: 6f1683ee7f39fb4c2718ad22c50e0226093985bc [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);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000747 ClassDecl->addDecl(Context, DefaultCon);
748
749 // Notify the class that we've added a constructor.
750 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000751 }
752
753 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
754 // C++ [class.copy]p4:
755 // If the class definition does not explicitly declare a copy
756 // constructor, one is declared implicitly.
757
758 // C++ [class.copy]p5:
759 // The implicitly-declared copy constructor for a class X will
760 // have the form
761 //
762 // X::X(const X&)
763 //
764 // if
765 bool HasConstCopyConstructor = true;
766
767 // -- each direct or virtual base class B of X has a copy
768 // constructor whose first parameter is of type const B& or
769 // const volatile B&, and
770 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
771 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
772 const CXXRecordDecl *BaseClassDecl
773 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
774 HasConstCopyConstructor
775 = BaseClassDecl->hasConstCopyConstructor(Context);
776 }
777
778 // -- for all the nonstatic data members of X that are of a
779 // class type M (or array thereof), each such class type
780 // has a copy constructor whose first parameter is of type
781 // const M& or const volatile M&.
782 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
783 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
784 QualType FieldType = (*Field)->getType();
785 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
786 FieldType = Array->getElementType();
787 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
788 const CXXRecordDecl *FieldClassDecl
789 = cast<CXXRecordDecl>(FieldClassType->getDecl());
790 HasConstCopyConstructor
791 = FieldClassDecl->hasConstCopyConstructor(Context);
792 }
793 }
794
795 // Otherwise, the implicitly declared copy constructor will have
796 // the form
797 //
798 // X::X(X&)
799 QualType ArgType = Context.getTypeDeclType(ClassDecl);
800 if (HasConstCopyConstructor)
801 ArgType = ArgType.withConst();
802 ArgType = Context.getReferenceType(ArgType);
803
804 // An implicitly-declared copy constructor is an inline public
805 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000806 DeclarationName Name
807 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000808 CXXConstructorDecl *CopyConstructor
809 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000810 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000811 Context.getFunctionType(Context.VoidTy,
812 &ArgType, 1,
813 false, 0),
814 /*isExplicit=*/false,
815 /*isInline=*/true,
816 /*isImplicitlyDeclared=*/true);
817 CopyConstructor->setAccess(AS_public);
818
819 // Add the parameter to the constructor.
820 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
821 ClassDecl->getLocation(),
822 /*IdentifierInfo=*/0,
823 ArgType, VarDecl::None, 0, 0);
824 CopyConstructor->setParams(&FromParam, 1);
825
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000826 ClassDecl->addedConstructor(Context, CopyConstructor);
827 DeclContext::lookup_result Lookup = ClassDecl->lookup(Context, Name);
828 if (Lookup.first == Lookup.second
829 || (!isa<CXXConstructorDecl>(*Lookup.first) &&
830 !isa<OverloadedFunctionDecl>(*Lookup.first)))
831 ClassDecl->addDecl(Context, CopyConstructor);
832 else {
833 OverloadedFunctionDecl *Ovl
834 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first);
835 if (!Ovl) {
836 Ovl = OverloadedFunctionDecl::Create(Context, ClassDecl, Name);
837 Ovl->addOverload(cast<CXXConstructorDecl>(*Lookup.first));
838 ClassDecl->insert(Context, Ovl);
839 }
840
841 Ovl->addOverload(CopyConstructor);
842 ClassDecl->addDecl(Context, CopyConstructor, false);
843 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000844 }
845
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000846 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000847 // C++ [class.dtor]p2:
848 // If a class has no user-declared destructor, a destructor is
849 // declared implicitly. An implicitly-declared destructor is an
850 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000851 DeclarationName Name
852 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000853 CXXDestructorDecl *Destructor
854 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000855 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000856 Context.getFunctionType(Context.VoidTy,
857 0, 0, false, 0),
858 /*isInline=*/true,
859 /*isImplicitlyDeclared=*/true);
860 Destructor->setAccess(AS_public);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000861 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000862 }
863
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000864 // FIXME: Implicit copy assignment operator
865}
866
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000867void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000868 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000869 FieldCollector->FinishClass();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000870 AddImplicitlyDeclaredMembersToClass(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000871 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000872
873 // Everything, including inline method definitions, have been parsed.
874 // Let the consumer know of the new TagDecl definition.
875 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000876}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000877
Douglas Gregor42a552f2008-11-05 20:51:48 +0000878/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
879/// the well-formednes of the constructor declarator @p D with type @p
880/// R. If there are any errors in the declarator, this routine will
881/// emit diagnostics and return true. Otherwise, it will return
882/// false. Either way, the type @p R will be updated to reflect a
883/// well-formed type for the constructor.
884bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
885 FunctionDecl::StorageClass& SC) {
886 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
887 bool isInvalid = false;
888
889 // C++ [class.ctor]p3:
890 // A constructor shall not be virtual (10.3) or static (9.4). A
891 // constructor can be invoked for a const, volatile or const
892 // volatile object. A constructor shall not be declared const,
893 // volatile, or const volatile (9.3.2).
894 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000895 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
896 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
897 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000898 isInvalid = true;
899 }
900 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000901 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
902 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
903 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000904 isInvalid = true;
905 SC = FunctionDecl::None;
906 }
907 if (D.getDeclSpec().hasTypeSpecifier()) {
908 // Constructors don't have return types, but the parser will
909 // happily parse something like:
910 //
911 // class X {
912 // float X(float);
913 // };
914 //
915 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000916 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
917 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
918 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000919 }
920 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
921 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
922 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000923 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
924 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000925 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000926 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
927 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000928 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000929 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
930 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000931 }
932
933 // Rebuild the function type "R" without any type qualifiers (in
934 // case any of the errors above fired) and with "void" as the
935 // return type, since constructors don't have return types. We
936 // *always* have to do this, because GetTypeForDeclarator will
937 // put in a result type of "int" when none was specified.
938 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
939 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
940 Proto->getNumArgs(),
941 Proto->isVariadic(),
942 0);
943
944 return isInvalid;
945}
946
947/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
948/// the well-formednes of the destructor declarator @p D with type @p
949/// R. If there are any errors in the declarator, this routine will
950/// emit diagnostics and return true. Otherwise, it will return
951/// false. Either way, the type @p R will be updated to reflect a
952/// well-formed type for the destructor.
953bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
954 FunctionDecl::StorageClass& SC) {
955 bool isInvalid = false;
956
957 // C++ [class.dtor]p1:
958 // [...] A typedef-name that names a class is a class-name
959 // (7.1.3); however, a typedef-name that names a class shall not
960 // be used as the identifier in the declarator for a destructor
961 // declaration.
962 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
963 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000964 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000965 << TypedefD->getDeclName();
Douglas Gregor55c60952008-11-10 14:41:22 +0000966 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000967 }
968
969 // C++ [class.dtor]p2:
970 // A destructor is used to destroy objects of its class type. A
971 // destructor takes no parameters, and no return type can be
972 // specified for it (not even void). The address of a destructor
973 // shall not be taken. A destructor shall not be static. A
974 // destructor can be invoked for a const, volatile or const
975 // volatile object. A destructor shall not be declared const,
976 // volatile or const volatile (9.3.2).
977 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000978 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
979 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
980 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000981 isInvalid = true;
982 SC = FunctionDecl::None;
983 }
984 if (D.getDeclSpec().hasTypeSpecifier()) {
985 // Destructors don't have return types, but the parser will
986 // happily parse something like:
987 //
988 // class X {
989 // float ~X();
990 // };
991 //
992 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000993 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
994 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
995 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000996 }
997 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
998 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
999 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001000 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1001 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001002 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001003 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1004 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001005 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001006 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1007 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001008 }
1009
1010 // Make sure we don't have any parameters.
1011 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1012 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1013
1014 // Delete the parameters.
1015 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1016 if (FTI.NumArgs) {
1017 delete [] FTI.ArgInfo;
1018 FTI.NumArgs = 0;
1019 FTI.ArgInfo = 0;
1020 }
1021 }
1022
1023 // Make sure the destructor isn't variadic.
1024 if (R->getAsFunctionTypeProto()->isVariadic())
1025 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1026
1027 // Rebuild the function type "R" without any type qualifiers or
1028 // parameters (in case any of the errors above fired) and with
1029 // "void" as the return type, since destructors don't have return
1030 // types. We *always* have to do this, because GetTypeForDeclarator
1031 // will put in a result type of "int" when none was specified.
1032 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1033
1034 return isInvalid;
1035}
1036
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001037/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1038/// well-formednes of the conversion function declarator @p D with
1039/// type @p R. If there are any errors in the declarator, this routine
1040/// will emit diagnostics and return true. Otherwise, it will return
1041/// false. Either way, the type @p R will be updated to reflect a
1042/// well-formed type for the conversion operator.
1043bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1044 FunctionDecl::StorageClass& SC) {
1045 bool isInvalid = false;
1046
1047 // C++ [class.conv.fct]p1:
1048 // Neither parameter types nor return type can be specified. The
1049 // type of a conversion function (8.3.5) is “function taking no
1050 // parameter returning conversion-type-id.”
1051 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001052 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1053 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1054 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001055 isInvalid = true;
1056 SC = FunctionDecl::None;
1057 }
1058 if (D.getDeclSpec().hasTypeSpecifier()) {
1059 // Conversion functions don't have return types, but the parser will
1060 // happily parse something like:
1061 //
1062 // class X {
1063 // float operator bool();
1064 // };
1065 //
1066 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001067 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1068 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1069 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001070 }
1071
1072 // Make sure we don't have any parameters.
1073 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1074 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1075
1076 // Delete the parameters.
1077 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1078 if (FTI.NumArgs) {
1079 delete [] FTI.ArgInfo;
1080 FTI.NumArgs = 0;
1081 FTI.ArgInfo = 0;
1082 }
1083 }
1084
1085 // Make sure the conversion function isn't variadic.
1086 if (R->getAsFunctionTypeProto()->isVariadic())
1087 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1088
1089 // C++ [class.conv.fct]p4:
1090 // The conversion-type-id shall not represent a function type nor
1091 // an array type.
1092 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1093 if (ConvType->isArrayType()) {
1094 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1095 ConvType = Context.getPointerType(ConvType);
1096 } else if (ConvType->isFunctionType()) {
1097 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1098 ConvType = Context.getPointerType(ConvType);
1099 }
1100
1101 // Rebuild the function type "R" without any parameters (in case any
1102 // of the errors above fired) and with the conversion type as the
1103 // return type.
1104 R = Context.getFunctionType(ConvType, 0, 0, false,
1105 R->getAsFunctionTypeProto()->getTypeQuals());
1106
1107 return isInvalid;
1108}
1109
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001110/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1111/// the declaration of the given C++ conversion function. This routine
1112/// is responsible for recording the conversion function in the C++
1113/// class, if possible.
1114Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1115 assert(Conversion && "Expected to receive a conversion function declaration");
1116
Douglas Gregor9d350972008-12-12 08:25:50 +00001117 // Set the lexical context of this conversion function
1118 Conversion->setLexicalDeclContext(CurContext);
1119
1120 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001121
1122 // Make sure we aren't redeclaring the conversion function.
1123 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1124 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1125 for (OverloadedFunctionDecl::function_iterator Func
1126 = Conversions->function_begin();
1127 Func != Conversions->function_end(); ++Func) {
1128 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1129 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1130 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1131 Diag(OtherConv->getLocation(),
1132 OtherConv->isThisDeclarationADefinition()?
Chris Lattner5f4a6822008-11-23 23:12:31 +00001133 diag::note_previous_definition
1134 : diag::note_previous_declaration);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001135 Conversion->setInvalidDecl();
1136 return (DeclTy *)Conversion;
1137 }
1138 }
1139
1140 // C++ [class.conv.fct]p1:
1141 // [...] A conversion function is never used to convert a
1142 // (possibly cv-qualified) object to the (possibly cv-qualified)
1143 // same object type (or a reference to it), to a (possibly
1144 // cv-qualified) base class of that type (or a reference to it),
1145 // or to (possibly cv-qualified) void.
1146 // FIXME: Suppress this warning if the conversion function ends up
1147 // being a virtual function that overrides a virtual function in a
1148 // base class.
1149 QualType ClassType
1150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1151 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1152 ConvType = ConvTypeRef->getPointeeType();
1153 if (ConvType->isRecordType()) {
1154 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1155 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001156 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001157 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001158 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001159 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001160 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001161 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001162 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001163 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001164 }
1165
1166 ClassDecl->addConversionFunction(Context, Conversion);
1167
1168 return (DeclTy *)Conversion;
1169}
1170
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001171//===----------------------------------------------------------------------===//
1172// Namespace Handling
1173//===----------------------------------------------------------------------===//
1174
1175/// ActOnStartNamespaceDef - This is called at the start of a namespace
1176/// definition.
1177Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1178 SourceLocation IdentLoc,
1179 IdentifierInfo *II,
1180 SourceLocation LBrace) {
1181 NamespaceDecl *Namespc =
1182 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1183 Namespc->setLBracLoc(LBrace);
1184
1185 Scope *DeclRegionScope = NamespcScope->getParent();
1186
1187 if (II) {
1188 // C++ [namespace.def]p2:
1189 // The identifier in an original-namespace-definition shall not have been
1190 // previously defined in the declarative region in which the
1191 // original-namespace-definition appears. The identifier in an
1192 // original-namespace-definition is the name of the namespace. Subsequently
1193 // in that declarative region, it is treated as an original-namespace-name.
1194
1195 Decl *PrevDecl =
Douglas Gregor44b43212008-12-11 16:49:14 +00001196 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1197 /*enableLazyBuiltinCreation=*/false,
1198 /*LookupInParent=*/false);
1199
1200 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1201 // This is an extended namespace definition.
1202 // Attach this namespace decl to the chain of extended namespace
1203 // definitions.
1204 OrigNS->setNextNamespace(Namespc);
1205 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001206
Douglas Gregor44b43212008-12-11 16:49:14 +00001207 // Remove the previous declaration from the scope.
1208 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001209 IdResolver.RemoveDecl(OrigNS);
1210 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001211 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001212 } else if (PrevDecl) {
1213 // This is an invalid name redefinition.
1214 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1215 << Namespc->getDeclName();
1216 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1217 Namespc->setInvalidDecl();
1218 // Continue on to push Namespc as current DeclContext and return it.
1219 }
1220
1221 PushOnScopeChains(Namespc, DeclRegionScope);
1222 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001223 // FIXME: Handle anonymous namespaces
1224 }
1225
1226 // Although we could have an invalid decl (i.e. the namespace name is a
1227 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001228 // FIXME: We should be able to push Namespc here, so that the
1229 // each DeclContext for the namespace has the declarations
1230 // that showed up in that particular namespace definition.
1231 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001232 return Namespc;
1233}
1234
1235/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1236/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1237void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1238 Decl *Dcl = static_cast<Decl *>(D);
1239 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1240 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1241 Namespc->setRBracLoc(RBrace);
1242 PopDeclContext();
1243}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001244
1245
1246/// AddCXXDirectInitializerToDecl - This action is called immediately after
1247/// ActOnDeclarator, when a C++ direct initializer is present.
1248/// e.g: "int x(1);"
1249void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1250 ExprTy **ExprTys, unsigned NumExprs,
1251 SourceLocation *CommaLocs,
1252 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001253 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001254 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001255
1256 // If there is no declaration, there was an error parsing it. Just ignore
1257 // the initializer.
1258 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001259 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001260 delete static_cast<Expr *>(ExprTys[i]);
1261 return;
1262 }
1263
1264 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1265 if (!VDecl) {
1266 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1267 RealDecl->setInvalidDecl();
1268 return;
1269 }
1270
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001271 // We will treat direct-initialization as a copy-initialization:
1272 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001273 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1274 //
1275 // Clients that want to distinguish between the two forms, can check for
1276 // direct initializer using VarDecl::hasCXXDirectInitializer().
1277 // A major benefit is that clients that don't particularly care about which
1278 // exactly form was it (like the CodeGen) can handle both cases without
1279 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001280
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001281 // C++ 8.5p11:
1282 // The form of initialization (using parentheses or '=') is generally
1283 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001284 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001285 QualType DeclInitType = VDecl->getType();
1286 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1287 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001288
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001289 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001290 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001291 = PerformInitializationByConstructor(DeclInitType,
1292 (Expr **)ExprTys, NumExprs,
1293 VDecl->getLocation(),
1294 SourceRange(VDecl->getLocation(),
1295 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001296 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001297 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001298 if (!Constructor) {
1299 RealDecl->setInvalidDecl();
1300 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001301
1302 // Let clients know that initialization was done with a direct
1303 // initializer.
1304 VDecl->setCXXDirectInitializer(true);
1305
1306 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1307 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001308 return;
1309 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001310
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001311 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001312 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1313 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001314 RealDecl->setInvalidDecl();
1315 return;
1316 }
1317
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001318 // Let clients know that initialization was done with a direct initializer.
1319 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001320
1321 assert(NumExprs == 1 && "Expected 1 expression");
1322 // Set the init expression, handles conversions.
Sebastian Redl798d1192008-12-13 16:23:55 +00001323 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001324}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001325
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001326/// PerformInitializationByConstructor - Perform initialization by
1327/// constructor (C++ [dcl.init]p14), which may occur as part of
1328/// direct-initialization or copy-initialization. We are initializing
1329/// an object of type @p ClassType with the given arguments @p
1330/// Args. @p Loc is the location in the source code where the
1331/// initializer occurs (e.g., a declaration, member initializer,
1332/// functional cast, etc.) while @p Range covers the whole
1333/// initialization. @p InitEntity is the entity being initialized,
1334/// which may by the name of a declaration or a type. @p Kind is the
1335/// kind of initialization we're performing, which affects whether
1336/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001337/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001338/// when the initialization fails, emits a diagnostic and returns
1339/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001340CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001341Sema::PerformInitializationByConstructor(QualType ClassType,
1342 Expr **Args, unsigned NumArgs,
1343 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001344 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001345 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001346 const RecordType *ClassRec = ClassType->getAsRecordType();
1347 assert(ClassRec && "Can only initialize a class type here");
1348
1349 // C++ [dcl.init]p14:
1350 //
1351 // If the initialization is direct-initialization, or if it is
1352 // copy-initialization where the cv-unqualified version of the
1353 // source type is the same class as, or a derived class of, the
1354 // class of the destination, constructors are considered. The
1355 // applicable constructors are enumerated (13.3.1.3), and the
1356 // best one is chosen through overload resolution (13.3). The
1357 // constructor so selected is called to initialize the object,
1358 // with the initializer expression(s) as its argument(s). If no
1359 // constructor applies, or the overload resolution is ambiguous,
1360 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001361 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1362 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001363
1364 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001365 DeclarationName ConstructorName
1366 = Context.DeclarationNames.getCXXConstructorName(
1367 Context.getCanonicalType(ClassType.getUnqualifiedType()));
1368 DeclContext::lookup_const_result Lookup
1369 = ClassDecl->lookup(Context, ConstructorName);
1370 if (Lookup.first == Lookup.second)
1371 /* No constructors */;
1372 else if (OverloadedFunctionDecl *Constructors
1373 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) {
1374 for (OverloadedFunctionDecl::function_iterator Con
1375 = Constructors->function_begin();
1376 Con != Constructors->function_end(); ++Con) {
1377 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1378 if ((Kind == IK_Direct) ||
1379 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1380 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1381 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1382 }
1383 } else if (CXXConstructorDecl *Constructor
1384 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001385 if ((Kind == IK_Direct) ||
1386 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1387 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1388 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1389 }
1390
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001391 // FIXME: When we decide not to synthesize the implicitly-declared
1392 // constructors, we'll need to make them appear here.
1393
Douglas Gregor18fe5682008-11-03 20:45:27 +00001394 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001395 switch (BestViableFunction(CandidateSet, Best)) {
1396 case OR_Success:
1397 // We found a constructor. Return it.
1398 return cast<CXXConstructorDecl>(Best->Function);
1399
1400 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001401 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1402 << InitEntity << (unsigned)CandidateSet.size() << Range;
1403 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001404 return 0;
1405
1406 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001407 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001408 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1409 return 0;
1410 }
1411
1412 return 0;
1413}
1414
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001415/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1416/// determine whether they are reference-related,
1417/// reference-compatible, reference-compatible with added
1418/// qualification, or incompatible, for use in C++ initialization by
1419/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1420/// type, and the first type (T1) is the pointee type of the reference
1421/// type being initialized.
1422Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001423Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1424 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001425 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1426 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1427
1428 T1 = Context.getCanonicalType(T1);
1429 T2 = Context.getCanonicalType(T2);
1430 QualType UnqualT1 = T1.getUnqualifiedType();
1431 QualType UnqualT2 = T2.getUnqualifiedType();
1432
1433 // C++ [dcl.init.ref]p4:
1434 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1435 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1436 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001437 if (UnqualT1 == UnqualT2)
1438 DerivedToBase = false;
1439 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1440 DerivedToBase = true;
1441 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001442 return Ref_Incompatible;
1443
1444 // At this point, we know that T1 and T2 are reference-related (at
1445 // least).
1446
1447 // C++ [dcl.init.ref]p4:
1448 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1449 // reference-related to T2 and cv1 is the same cv-qualification
1450 // as, or greater cv-qualification than, cv2. For purposes of
1451 // overload resolution, cases for which cv1 is greater
1452 // cv-qualification than cv2 are identified as
1453 // reference-compatible with added qualification (see 13.3.3.2).
1454 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1455 return Ref_Compatible;
1456 else if (T1.isMoreQualifiedThan(T2))
1457 return Ref_Compatible_With_Added_Qualification;
1458 else
1459 return Ref_Related;
1460}
1461
1462/// CheckReferenceInit - Check the initialization of a reference
1463/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1464/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001465/// list), and DeclType is the type of the declaration. When ICS is
1466/// non-null, this routine will compute the implicit conversion
1467/// sequence according to C++ [over.ics.ref] and will not produce any
1468/// diagnostics; when ICS is null, it will emit diagnostics when any
1469/// errors are found. Either way, a return value of true indicates
1470/// that there was a failure, a return value of false indicates that
1471/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001472///
1473/// When @p SuppressUserConversions, user-defined conversions are
1474/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001475bool
1476Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001477 ImplicitConversionSequence *ICS,
1478 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001479 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1480
1481 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1482 QualType T2 = Init->getType();
1483
Douglas Gregor904eed32008-11-10 20:40:00 +00001484 // If the initializer is the address of an overloaded function, try
1485 // to resolve the overloaded function. If all goes well, T2 is the
1486 // type of the resulting function.
1487 if (T2->isOverloadType()) {
1488 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1489 ICS != 0);
1490 if (Fn) {
1491 // Since we're performing this reference-initialization for
1492 // real, update the initializer with the resulting function.
1493 if (!ICS)
1494 FixOverloadedFunctionReference(Init, Fn);
1495
1496 T2 = Fn->getType();
1497 }
1498 }
1499
Douglas Gregor15da57e2008-10-29 02:00:59 +00001500 // Compute some basic properties of the types and the initializer.
1501 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001502 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001503 ReferenceCompareResult RefRelationship
1504 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1505
1506 // Most paths end in a failed conversion.
1507 if (ICS)
1508 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001509
1510 // C++ [dcl.init.ref]p5:
1511 // A reference to type “cv1 T1” is initialized by an expression
1512 // of type “cv2 T2” as follows:
1513
1514 // -- If the initializer expression
1515
1516 bool BindsDirectly = false;
1517 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1518 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001519 //
1520 // Note that the bit-field check is skipped if we are just computing
1521 // the implicit conversion sequence (C++ [over.best.ics]p2).
1522 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1523 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001524 BindsDirectly = true;
1525
Douglas Gregor15da57e2008-10-29 02:00:59 +00001526 if (ICS) {
1527 // C++ [over.ics.ref]p1:
1528 // When a parameter of reference type binds directly (8.5.3)
1529 // to an argument expression, the implicit conversion sequence
1530 // is the identity conversion, unless the argument expression
1531 // has a type that is a derived class of the parameter type,
1532 // in which case the implicit conversion sequence is a
1533 // derived-to-base Conversion (13.3.3.1).
1534 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1535 ICS->Standard.First = ICK_Identity;
1536 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1537 ICS->Standard.Third = ICK_Identity;
1538 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1539 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001540 ICS->Standard.ReferenceBinding = true;
1541 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001542
1543 // Nothing more to do: the inaccessibility/ambiguity check for
1544 // derived-to-base conversions is suppressed when we're
1545 // computing the implicit conversion sequence (C++
1546 // [over.best.ics]p2).
1547 return false;
1548 } else {
1549 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001550 // FIXME: Binding to a subobject of the lvalue is going to require
1551 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001552 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001553 }
1554 }
1555
1556 // -- has a class type (i.e., T2 is a class type) and can be
1557 // implicitly converted to an lvalue of type “cv3 T3,”
1558 // where “cv1 T1” is reference-compatible with “cv3 T3”
1559 // 92) (this conversion is selected by enumerating the
1560 // applicable conversion functions (13.3.1.6) and choosing
1561 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001562 if (!SuppressUserConversions && T2->isRecordType()) {
1563 // FIXME: Look for conversions in base classes!
1564 CXXRecordDecl *T2RecordDecl
1565 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001566
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001567 OverloadCandidateSet CandidateSet;
1568 OverloadedFunctionDecl *Conversions
1569 = T2RecordDecl->getConversionFunctions();
1570 for (OverloadedFunctionDecl::function_iterator Func
1571 = Conversions->function_begin();
1572 Func != Conversions->function_end(); ++Func) {
1573 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1574
1575 // If the conversion function doesn't return a reference type,
1576 // it can't be considered for this conversion.
1577 // FIXME: This will change when we support rvalue references.
1578 if (Conv->getConversionType()->isReferenceType())
1579 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1580 }
1581
1582 OverloadCandidateSet::iterator Best;
1583 switch (BestViableFunction(CandidateSet, Best)) {
1584 case OR_Success:
1585 // This is a direct binding.
1586 BindsDirectly = true;
1587
1588 if (ICS) {
1589 // C++ [over.ics.ref]p1:
1590 //
1591 // [...] If the parameter binds directly to the result of
1592 // applying a conversion function to the argument
1593 // expression, the implicit conversion sequence is a
1594 // user-defined conversion sequence (13.3.3.1.2), with the
1595 // second standard conversion sequence either an identity
1596 // conversion or, if the conversion function returns an
1597 // entity of a type that is a derived class of the parameter
1598 // type, a derived-to-base Conversion.
1599 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1600 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1601 ICS->UserDefined.After = Best->FinalConversion;
1602 ICS->UserDefined.ConversionFunction = Best->Function;
1603 assert(ICS->UserDefined.After.ReferenceBinding &&
1604 ICS->UserDefined.After.DirectBinding &&
1605 "Expected a direct reference binding!");
1606 return false;
1607 } else {
1608 // Perform the conversion.
1609 // FIXME: Binding to a subobject of the lvalue is going to require
1610 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001611 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001612 }
1613 break;
1614
1615 case OR_Ambiguous:
1616 assert(false && "Ambiguous reference binding conversions not implemented.");
1617 return true;
1618
1619 case OR_No_Viable_Function:
1620 // There was no suitable conversion; continue with other checks.
1621 break;
1622 }
1623 }
1624
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001625 if (BindsDirectly) {
1626 // C++ [dcl.init.ref]p4:
1627 // [...] In all cases where the reference-related or
1628 // reference-compatible relationship of two types is used to
1629 // establish the validity of a reference binding, and T1 is a
1630 // base class of T2, a program that necessitates such a binding
1631 // is ill-formed if T1 is an inaccessible (clause 11) or
1632 // ambiguous (10.2) base class of T2.
1633 //
1634 // Note that we only check this condition when we're allowed to
1635 // complain about errors, because we should not be checking for
1636 // ambiguity (or inaccessibility) unless the reference binding
1637 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001638 if (DerivedToBase)
1639 return CheckDerivedToBaseConversion(T2, T1,
1640 Init->getSourceRange().getBegin(),
1641 Init->getSourceRange());
1642 else
1643 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001644 }
1645
1646 // -- Otherwise, the reference shall be to a non-volatile const
1647 // type (i.e., cv1 shall be const).
1648 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001649 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001650 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001651 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001652 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1653 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001654 return true;
1655 }
1656
1657 // -- If the initializer expression is an rvalue, with T2 a
1658 // class type, and “cv1 T1” is reference-compatible with
1659 // “cv2 T2,” the reference is bound in one of the
1660 // following ways (the choice is implementation-defined):
1661 //
1662 // -- The reference is bound to the object represented by
1663 // the rvalue (see 3.10) or to a sub-object within that
1664 // object.
1665 //
1666 // -- A temporary of type “cv1 T2” [sic] is created, and
1667 // a constructor is called to copy the entire rvalue
1668 // object into the temporary. The reference is bound to
1669 // the temporary or to a sub-object within the
1670 // temporary.
1671 //
1672 //
1673 // The constructor that would be used to make the copy
1674 // shall be callable whether or not the copy is actually
1675 // done.
1676 //
1677 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1678 // freedom, so we will always take the first option and never build
1679 // a temporary in this case. FIXME: We will, however, have to check
1680 // for the presence of a copy constructor in C++98/03 mode.
1681 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001682 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1683 if (ICS) {
1684 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1685 ICS->Standard.First = ICK_Identity;
1686 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1687 ICS->Standard.Third = ICK_Identity;
1688 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1689 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001690 ICS->Standard.ReferenceBinding = true;
1691 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001692 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001693 // FIXME: Binding to a subobject of the rvalue is going to require
1694 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001695 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001696 }
1697 return false;
1698 }
1699
1700 // -- Otherwise, a temporary of type “cv1 T1” is created and
1701 // initialized from the initializer expression using the
1702 // rules for a non-reference copy initialization (8.5). The
1703 // reference is then bound to the temporary. If T1 is
1704 // reference-related to T2, cv1 must be the same
1705 // cv-qualification as, or greater cv-qualification than,
1706 // cv2; otherwise, the program is ill-formed.
1707 if (RefRelationship == Ref_Related) {
1708 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1709 // we would be reference-compatible or reference-compatible with
1710 // added qualification. But that wasn't the case, so the reference
1711 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001712 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001713 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001714 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001715 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1716 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001717 return true;
1718 }
1719
1720 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001721 if (ICS) {
1722 /// C++ [over.ics.ref]p2:
1723 ///
1724 /// When a parameter of reference type is not bound directly to
1725 /// an argument expression, the conversion sequence is the one
1726 /// required to convert the argument expression to the
1727 /// underlying type of the reference according to
1728 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1729 /// to copy-initializing a temporary of the underlying type with
1730 /// the argument expression. Any difference in top-level
1731 /// cv-qualification is subsumed by the initialization itself
1732 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001733 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001734 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1735 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001736 return PerformImplicitConversion(Init, T1);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001737 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001738}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001739
1740/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1741/// of this overloaded operator is well-formed. If so, returns false;
1742/// otherwise, emits appropriate diagnostics and returns true.
1743bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001744 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001745 "Expected an overloaded operator declaration");
1746
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001747 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1748
1749 // C++ [over.oper]p5:
1750 // The allocation and deallocation functions, operator new,
1751 // operator new[], operator delete and operator delete[], are
1752 // described completely in 3.7.3. The attributes and restrictions
1753 // found in the rest of this subclause do not apply to them unless
1754 // explicitly stated in 3.7.3.
1755 // FIXME: Write a separate routine for checking this. For now, just
1756 // allow it.
1757 if (Op == OO_New || Op == OO_Array_New ||
1758 Op == OO_Delete || Op == OO_Array_Delete)
1759 return false;
1760
1761 // C++ [over.oper]p6:
1762 // An operator function shall either be a non-static member
1763 // function or be a non-member function and have at least one
1764 // parameter whose type is a class, a reference to a class, an
1765 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001766 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1767 if (MethodDecl->isStatic())
1768 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001769 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001770 } else {
1771 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001772 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1773 ParamEnd = FnDecl->param_end();
1774 Param != ParamEnd; ++Param) {
1775 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001776 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1777 ClassOrEnumParam = true;
1778 break;
1779 }
1780 }
1781
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001782 if (!ClassOrEnumParam)
1783 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001784 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001785 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001786 }
1787
1788 // C++ [over.oper]p8:
1789 // An operator function cannot have default arguments (8.3.6),
1790 // except where explicitly stated below.
1791 //
1792 // Only the function-call operator allows default arguments
1793 // (C++ [over.call]p1).
1794 if (Op != OO_Call) {
1795 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1796 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001797 if (Expr *DefArg = (*Param)->getDefaultArg())
1798 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001799 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001800 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001801 }
1802 }
1803
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001804 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1805 { false, false, false }
1806#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1807 , { Unary, Binary, MemberOnly }
1808#include "clang/Basic/OperatorKinds.def"
1809 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001810
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001811 bool CanBeUnaryOperator = OperatorUses[Op][0];
1812 bool CanBeBinaryOperator = OperatorUses[Op][1];
1813 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001814
1815 // C++ [over.oper]p8:
1816 // [...] Operator functions cannot have more or fewer parameters
1817 // than the number required for the corresponding operator, as
1818 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001819 unsigned NumParams = FnDecl->getNumParams()
1820 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001821 if (Op != OO_Call &&
1822 ((NumParams == 1 && !CanBeUnaryOperator) ||
1823 (NumParams == 2 && !CanBeBinaryOperator) ||
1824 (NumParams < 1) || (NumParams > 2))) {
1825 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00001826 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001827 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001828 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001829 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001830 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001831 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001832 assert(CanBeBinaryOperator &&
1833 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00001834 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001835 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001836
Chris Lattner416e46f2008-11-21 07:57:12 +00001837 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001838 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001839 }
1840
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001841 // Overloaded operators other than operator() cannot be variadic.
1842 if (Op != OO_Call &&
1843 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001844 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001845 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001846 }
1847
1848 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001849 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1850 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001851 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001852 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001853 }
1854
1855 // C++ [over.inc]p1:
1856 // The user-defined function called operator++ implements the
1857 // prefix and postfix ++ operator. If this function is a member
1858 // function with no parameters, or a non-member function with one
1859 // parameter of class or enumeration type, it defines the prefix
1860 // increment operator ++ for objects of that type. If the function
1861 // is a member function with one parameter (which shall be of type
1862 // int) or a non-member function with two parameters (the second
1863 // of which shall be of type int), it defines the postfix
1864 // increment operator ++ for objects of that type.
1865 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1866 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1867 bool ParamIsInt = false;
1868 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1869 ParamIsInt = BT->getKind() == BuiltinType::Int;
1870
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001871 if (!ParamIsInt)
1872 return Diag(LastParam->getLocation(),
1873 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00001874 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001875 }
1876
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001877 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001878}