blob: 02c2e9bbfab37989641861209339ce9d4ea7a0de [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/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.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;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000111 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();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattner3d1cee32008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor61366e92008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000144 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146
Chris Lattner3d1cee32008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor61366e92008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor72b505b2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor61366e92008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattner3d1cee32008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
204// type. Subroutine of MergeFunctionDecl.
205FunctionDecl *
206Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 // C++ [dcl.fct.default]p4:
208 //
209 // For non-template functions, default arguments can be added in
210 // later declarations of a function in the same
211 // scope. Declarations in different scopes have completely
212 // distinct sets of default arguments. That is, declarations in
213 // inner scopes do not acquire default arguments from
214 // declarations in outer scopes, and vice versa. In a given
215 // function declaration, all parameters subsequent to a
216 // parameter with a default argument shall have default
217 // arguments supplied in this or previous declarations. A
218 // default argument shall not be redefined by a later
219 // declaration (not even to the same value).
220 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
221 ParmVarDecl *OldParam = Old->getParamDecl(p);
222 ParmVarDecl *NewParam = New->getParamDecl(p);
223
224 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
225 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000226 diag::err_param_default_argument_redefinition)
227 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000228 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000229 } else if (OldParam->getDefaultArg()) {
230 // Merge the old default argument into the new parameter
231 NewParam->setDefaultArg(OldParam->getDefaultArg());
232 }
233 }
234
235 return New;
236}
237
238/// CheckCXXDefaultArguments - Verify that the default arguments for a
239/// function declaration are well-formed according to C++
240/// [dcl.fct.default].
241void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
242 unsigned NumParams = FD->getNumParams();
243 unsigned p;
244
245 // Find first parameter with a default argument
246 for (p = 0; p < NumParams; ++p) {
247 ParmVarDecl *Param = FD->getParamDecl(p);
248 if (Param->getDefaultArg())
249 break;
250 }
251
252 // C++ [dcl.fct.default]p4:
253 // In a given function declaration, all parameters
254 // subsequent to a parameter with a default argument shall
255 // have default arguments supplied in this or previous
256 // declarations. A default argument shall not be redefined
257 // by a later declaration (not even to the same value).
258 unsigned LastMissingDefaultArg = 0;
259 for(; p < NumParams; ++p) {
260 ParmVarDecl *Param = FD->getParamDecl(p);
261 if (!Param->getDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000262 if (Param->isInvalidDecl())
263 /* We already complained about this parameter. */;
264 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000265 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000266 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000267 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 else
269 Diag(Param->getLocation(),
270 diag::err_param_default_argument_missing);
271
272 LastMissingDefaultArg = p;
273 }
274 }
275
276 if (LastMissingDefaultArg > 0) {
277 // Some default arguments were missing. Clear out all of the
278 // default arguments up to (and including) the last missing
279 // default argument, so that we leave the function parameters
280 // in a semantically valid state.
281 for (p = 0; p <= LastMissingDefaultArg; ++p) {
282 ParmVarDecl *Param = FD->getParamDecl(p);
283 if (Param->getDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000284 if (!Param->hasUnparsedDefaultArg())
285 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000286 Param->setDefaultArg(0);
287 }
288 }
289 }
290}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000291
Douglas Gregorb48fe382008-10-31 09:07:45 +0000292/// isCurrentClassName - Determine whether the identifier II is the
293/// name of the class type currently being defined. In the case of
294/// nested classes, this will only return true if II is the name of
295/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000296bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
297 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000298 CXXRecordDecl *CurDecl;
299 if (SS) {
300 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
301 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
302 } else
303 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
304
305 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000306 return &II == CurDecl->getIdentifier();
307 else
308 return false;
309}
310
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000311/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
312/// one entry in the base class list of a class specifier, for
313/// example:
314/// class foo : public bar, virtual private baz {
315/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000316Sema::BaseResult
317Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
318 bool Virtual, AccessSpecifier Access,
319 TypeTy *basetype, SourceLocation BaseLoc) {
Sebastian Redl64b45f72009-01-05 20:52:13 +0000320 CXXRecordDecl *Decl = (CXXRecordDecl*)classdecl;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000321 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000322
323 // Base specifiers must be record types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000324 if (!BaseType->isRecordType())
325 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000326
327 // C++ [class.union]p1:
328 // A union shall not be used as a base class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000329 if (BaseType->isUnionType())
330 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000331
332 // C++ [class.union]p1:
333 // A union shall not have base classes.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000334 if (Decl->isUnion())
335 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
336 << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000337
338 // C++ [class.derived]p2:
339 // The class-name in a base-specifier shall not be an incompletely
340 // defined class.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000341 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
342 SpecifierRange))
343 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000344
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000345 // If the base class is polymorphic, the new one is, too.
346 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
347 assert(BaseDecl && "Record type has no declaration");
348 BaseDecl = BaseDecl->getDefinition(Context);
349 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000350 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl64b45f72009-01-05 20:52:13 +0000351 Decl->setPolymorphic(true);
352
353 // C++ [dcl.init.aggr]p1:
354 // An aggregate is [...] a class with [...] no base classes [...].
355 Decl->setAggregate(false);
356 Decl->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000357
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000358 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000359 return new CXXBaseSpecifier(SpecifierRange, Virtual,
360 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000361}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000362
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000363/// ActOnBaseSpecifiers - Attach the given base specifiers to the
364/// class, after checking whether there are any duplicate base
365/// classes.
366void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
367 unsigned NumBases) {
368 if (NumBases == 0)
369 return;
370
371 // Used to keep track of which base types we have already seen, so
372 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000373 // that the key is always the unqualified canonical type of the base
374 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000375 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
376
377 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000378 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
379 unsigned NumGoodBases = 0;
380 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000381 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000382 = Context.getCanonicalType(BaseSpecs[idx]->getType());
383 NewBaseType = NewBaseType.getUnqualifiedType();
384
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000385 if (KnownBaseTypes[NewBaseType]) {
386 // C++ [class.mi]p3:
387 // A class shall not be specified as a direct base class of a
388 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000389 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000390 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000391 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000392 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000393
394 // Delete the duplicate base class specifier; we're going to
395 // overwrite its pointer later.
396 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000397 } else {
398 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000399 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
400 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000401 }
402 }
403
404 // Attach the remaining base class specifiers to the derived class.
405 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000406 Decl->setBases(BaseSpecs, NumGoodBases);
407
408 // Delete the remaining (good) base class specifiers, since their
409 // data has been copied into the CXXRecordDecl.
410 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
411 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000412}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000413
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000414//===----------------------------------------------------------------------===//
415// C++ class member Handling
416//===----------------------------------------------------------------------===//
417
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000418/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
419/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
420/// bitfield width if there is one and 'InitExpr' specifies the initializer if
421/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
422/// declarators on it.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000423Sema::DeclTy *
424Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
425 ExprTy *BW, ExprTy *InitExpr,
426 DeclTy *LastInGroup) {
427 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000428 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000429 Expr *BitWidth = static_cast<Expr*>(BW);
430 Expr *Init = static_cast<Expr*>(InitExpr);
431 SourceLocation Loc = D.getIdentifierLoc();
432
Sebastian Redl669d5d72008-11-14 23:42:31 +0000433 bool isFunc = D.isFunctionDeclarator();
434
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000435 // C++ 9.2p6: A member shall not be declared to have automatic storage
436 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000437 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
438 // data members and cannot be applied to names declared const or static,
439 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000440 switch (DS.getStorageClassSpec()) {
441 case DeclSpec::SCS_unspecified:
442 case DeclSpec::SCS_typedef:
443 case DeclSpec::SCS_static:
444 // FALL THROUGH.
445 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000446 case DeclSpec::SCS_mutable:
447 if (isFunc) {
448 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000449 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000450 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000451 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
452
Sebastian Redla11f42f2008-11-17 23:24:37 +0000453 // FIXME: It would be nicer if the keyword was ignored only for this
454 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000455 D.getMutableDeclSpec().ClearStorageClassSpecs();
456 } else {
457 QualType T = GetTypeForDeclarator(D, S);
458 diag::kind err = static_cast<diag::kind>(0);
459 if (T->isReferenceType())
460 err = diag::err_mutable_reference;
461 else if (T.isConstQualified())
462 err = diag::err_mutable_const;
463 if (err != 0) {
464 if (DS.getStorageClassSpecLoc().isValid())
465 Diag(DS.getStorageClassSpecLoc(), err);
466 else
467 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000468 // FIXME: It would be nicer if the keyword was ignored only for this
469 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000470 D.getMutableDeclSpec().ClearStorageClassSpecs();
471 }
472 }
473 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000474 default:
475 if (DS.getStorageClassSpecLoc().isValid())
476 Diag(DS.getStorageClassSpecLoc(),
477 diag::err_storageclass_invalid_for_member);
478 else
479 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
480 D.getMutableDeclSpec().ClearStorageClassSpecs();
481 }
482
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000483 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000484 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000485 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000486 // Check also for this case:
487 //
488 // typedef int f();
489 // f a;
490 //
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000491 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
492 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000493 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000494
Sebastian Redl669d5d72008-11-14 23:42:31 +0000495 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
496 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000497 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000498
499 Decl *Member;
500 bool InvalidDecl = false;
501
502 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000503 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
504 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000505 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000506 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000507
508 if (!Member) return LastInGroup;
509
Douglas Gregor10bd3682008-11-17 22:58:34 +0000510 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000511
512 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
513 // specific methods. Use a wrapper class that can be used with all C++ class
514 // member decls.
515 CXXClassMemberWrapper(Member).setAccess(AS);
516
Douglas Gregor64bffa92008-11-05 16:20:31 +0000517 // C++ [dcl.init.aggr]p1:
518 // An aggregate is an array or a class (clause 9) with [...] no
519 // private or protected non-static data members (clause 11).
Sebastian Redl64b45f72009-01-05 20:52:13 +0000520 // A POD must be an aggregate.
521 if (isInstField && (AS == AS_private || AS == AS_protected)) {
522 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
523 Record->setAggregate(false);
524 Record->setPOD(false);
525 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000526
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000527 if (DS.isVirtualSpecified()) {
528 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
529 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
530 InvalidDecl = true;
531 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000532 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000533 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
534 CurClass->setAggregate(false);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000535 CurClass->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000536 CurClass->setPolymorphic(true);
537 }
538 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000539
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000540 // FIXME: The above definition of virtual is not sufficient. A function is
541 // also virtual if it overrides an already virtual function. This is important
542 // to do here because it decides the validity of a pure specifier.
543
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000544 if (BitWidth) {
545 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
546 // constant-expression be a value equal to zero.
547 // FIXME: Check this.
548
549 if (D.isFunctionDeclarator()) {
550 // FIXME: Emit diagnostic about only constructors taking base initializers
551 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000552 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000553 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000554 InvalidDecl = true;
555
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000556 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000557 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000558 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000559 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000560 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000561 InvalidDecl = true;
562 }
563
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000564 } else if (isa<FunctionDecl>(Member)) {
565 // A function typedef ("typedef int f(); f a;").
566 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000567 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000568 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000569 InvalidDecl = true;
570
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000571 } else if (isa<TypedefDecl>(Member)) {
572 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000573 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000574 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000575 InvalidDecl = true;
576
577 } else {
578 assert(isa<CXXClassVarDecl>(Member) &&
579 "Didn't we cover all member kinds?");
580 // C++ 9.6p3: A bit-field shall not be a static member.
581 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000582 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000583 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000584 InvalidDecl = true;
585 }
586 }
587
588 if (Init) {
589 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
590 // if it declares a static member of const integral or const enumeration
591 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000592 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
593 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000594 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000596 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
597 CVD->getType()->isIntegralType()) {
598 // constant-initializer
599 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000600 InvalidDecl = true;
601
602 } else {
603 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000604 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000605 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000606 InvalidDecl = true;
607 }
608
609 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000610 // not static member. perhaps virtual function?
611 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redlc9b580a2009-01-09 22:29:03 +0000612 // With declarators parsed the way they are, the parser cannot
613 // distinguish between a normal initializer and a pure-specifier.
614 // Thus this grotesque test.
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000615 IntegerLiteral *IL;
616 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
617 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
618 if (MD->isVirtual())
619 MD->setPure();
620 else {
621 Diag(Loc, diag::err_non_virtual_pure)
622 << Name << Init->getSourceRange();
623 InvalidDecl = true;
624 }
625 } else {
626 Diag(Loc, diag::err_member_function_initialization)
627 << Name << Init->getSourceRange();
628 InvalidDecl = true;
629 }
630 } else {
631 Diag(Loc, diag::err_member_initialization)
632 << Name << Init->getSourceRange();
633 InvalidDecl = true;
634 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000635 }
636 }
637
638 if (InvalidDecl)
639 Member->setInvalidDecl();
640
641 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000642 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000643 return LastInGroup;
644 }
645 return Member;
646}
647
Douglas Gregor7ad83902008-11-05 04:29:56 +0000648/// ActOnMemInitializer - Handle a C++ member initializer.
649Sema::MemInitResult
650Sema::ActOnMemInitializer(DeclTy *ConstructorD,
651 Scope *S,
652 IdentifierInfo *MemberOrBase,
653 SourceLocation IdLoc,
654 SourceLocation LParenLoc,
655 ExprTy **Args, unsigned NumArgs,
656 SourceLocation *CommaLocs,
657 SourceLocation RParenLoc) {
658 CXXConstructorDecl *Constructor
659 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
660 if (!Constructor) {
661 // The user wrote a constructor initializer on a function that is
662 // not a C++ constructor. Ignore the error for now, because we may
663 // have more member initializers coming; we'll diagnose it just
664 // once in ActOnMemInitializers.
665 return true;
666 }
667
668 CXXRecordDecl *ClassDecl = Constructor->getParent();
669
670 // C++ [class.base.init]p2:
671 // Names in a mem-initializer-id are looked up in the scope of the
672 // constructor’s class and, if not found in that scope, are looked
673 // up in the scope containing the constructor’s
674 // definition. [Note: if the constructor’s class contains a member
675 // with the same name as a direct or virtual base class of the
676 // class, a mem-initializer-id naming the member or base class and
677 // composed of a single identifier refers to the class member. A
678 // mem-initializer-id for the hidden base class may be specified
679 // using a qualified name. ]
680 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000681 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000682 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000683 if (Result.first != Result.second)
684 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000685
686 // FIXME: Handle members of an anonymous union.
687
688 if (Member) {
689 // FIXME: Perform direct initialization of the member.
690 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
691 }
692
693 // It didn't name a member, so see if it names a class.
Douglas Gregorb696ea32009-02-04 17:00:24 +0000694 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000695 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000696 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
697 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000698
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000699 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000700 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000701 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000702 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000703
704 // C++ [class.base.init]p2:
705 // [...] Unless the mem-initializer-id names a nonstatic data
706 // member of the constructor’s class or a direct or virtual base
707 // of that class, the mem-initializer is ill-formed. A
708 // mem-initializer-list can initialize a base class using any
709 // name that denotes that base class type.
710
711 // First, check for a direct base class.
712 const CXXBaseSpecifier *DirectBaseSpec = 0;
713 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
714 Base != ClassDecl->bases_end(); ++Base) {
715 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
716 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
717 // We found a direct base of this type. That's what we're
718 // initializing.
719 DirectBaseSpec = &*Base;
720 break;
721 }
722 }
723
724 // Check for a virtual base class.
725 // FIXME: We might be able to short-circuit this if we know in
726 // advance that there are no virtual bases.
727 const CXXBaseSpecifier *VirtualBaseSpec = 0;
728 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
729 // We haven't found a base yet; search the class hierarchy for a
730 // virtual base class.
731 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
732 /*DetectVirtual=*/false);
733 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
734 for (BasePaths::paths_iterator Path = Paths.begin();
735 Path != Paths.end(); ++Path) {
736 if (Path->back().Base->isVirtual()) {
737 VirtualBaseSpec = Path->back().Base;
738 break;
739 }
740 }
741 }
742 }
743
744 // C++ [base.class.init]p2:
745 // If a mem-initializer-id is ambiguous because it designates both
746 // a direct non-virtual base class and an inherited virtual base
747 // class, the mem-initializer is ill-formed.
748 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000749 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
750 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000751
752 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
753}
754
755
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000756void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
757 DeclTy *TagDecl,
758 SourceLocation LBrac,
759 SourceLocation RBrac) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000760 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000761 ActOnFields(S, RLoc, TagDecl,
762 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000763 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor61366e92008-12-24 00:01:03 +0000764 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000765}
766
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000767/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
768/// special functions, such as the default constructor, copy
769/// constructor, or destructor, to the given C++ class (C++
770/// [special]p1). This routine can only be executed just before the
771/// definition of the class is complete.
772void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000773 QualType ClassType = Context.getTypeDeclType(ClassDecl);
774 ClassType = Context.getCanonicalType(ClassType);
775
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000776 if (!ClassDecl->hasUserDeclaredConstructor()) {
777 // C++ [class.ctor]p5:
778 // A default constructor for a class X is a constructor of class X
779 // that can be called without an argument. If there is no
780 // user-declared constructor for class X, a default constructor is
781 // implicitly declared. An implicitly-declared default constructor
782 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000783 DeclarationName Name
784 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000785 CXXConstructorDecl *DefaultCon =
786 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000787 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000788 Context.getFunctionType(Context.VoidTy,
789 0, 0, false, 0),
790 /*isExplicit=*/false,
791 /*isInline=*/true,
792 /*isImplicitlyDeclared=*/true);
793 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000794 DefaultCon->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000795 ClassDecl->addDecl(DefaultCon);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000796
797 // Notify the class that we've added a constructor.
798 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000799 }
800
801 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
802 // C++ [class.copy]p4:
803 // If the class definition does not explicitly declare a copy
804 // constructor, one is declared implicitly.
805
806 // C++ [class.copy]p5:
807 // The implicitly-declared copy constructor for a class X will
808 // have the form
809 //
810 // X::X(const X&)
811 //
812 // if
813 bool HasConstCopyConstructor = true;
814
815 // -- each direct or virtual base class B of X has a copy
816 // constructor whose first parameter is of type const B& or
817 // const volatile B&, and
818 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
819 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
820 const CXXRecordDecl *BaseClassDecl
821 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
822 HasConstCopyConstructor
823 = BaseClassDecl->hasConstCopyConstructor(Context);
824 }
825
826 // -- for all the nonstatic data members of X that are of a
827 // class type M (or array thereof), each such class type
828 // has a copy constructor whose first parameter is of type
829 // const M& or const volatile M&.
830 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
831 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
832 QualType FieldType = (*Field)->getType();
833 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
834 FieldType = Array->getElementType();
835 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
836 const CXXRecordDecl *FieldClassDecl
837 = cast<CXXRecordDecl>(FieldClassType->getDecl());
838 HasConstCopyConstructor
839 = FieldClassDecl->hasConstCopyConstructor(Context);
840 }
841 }
842
Sebastian Redl64b45f72009-01-05 20:52:13 +0000843 // Otherwise, the implicitly declared copy constructor will have
844 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000845 //
846 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +0000847 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000848 if (HasConstCopyConstructor)
849 ArgType = ArgType.withConst();
850 ArgType = Context.getReferenceType(ArgType);
851
Sebastian Redl64b45f72009-01-05 20:52:13 +0000852 // An implicitly-declared copy constructor is an inline public
853 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000854 DeclarationName Name
855 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000856 CXXConstructorDecl *CopyConstructor
857 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000858 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000859 Context.getFunctionType(Context.VoidTy,
860 &ArgType, 1,
861 false, 0),
862 /*isExplicit=*/false,
863 /*isInline=*/true,
864 /*isImplicitlyDeclared=*/true);
865 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000866 CopyConstructor->setImplicit();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000867
868 // Add the parameter to the constructor.
869 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
870 ClassDecl->getLocation(),
871 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000872 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000873 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000874
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000875 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor482b77d2009-01-12 23:27:07 +0000876 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000877 }
878
Sebastian Redl64b45f72009-01-05 20:52:13 +0000879 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
880 // Note: The following rules are largely analoguous to the copy
881 // constructor rules. Note that virtual bases are not taken into account
882 // for determining the argument type of the operator. Note also that
883 // operators taking an object instead of a reference are allowed.
884 //
885 // C++ [class.copy]p10:
886 // If the class definition does not explicitly declare a copy
887 // assignment operator, one is declared implicitly.
888 // The implicitly-defined copy assignment operator for a class X
889 // will have the form
890 //
891 // X& X::operator=(const X&)
892 //
893 // if
894 bool HasConstCopyAssignment = true;
895
896 // -- each direct base class B of X has a copy assignment operator
897 // whose parameter is of type const B&, const volatile B& or B,
898 // and
899 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
900 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
901 const CXXRecordDecl *BaseClassDecl
902 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
903 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
904 }
905
906 // -- for all the nonstatic data members of X that are of a class
907 // type M (or array thereof), each such class type has a copy
908 // assignment operator whose parameter is of type const M&,
909 // const volatile M& or M.
910 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
911 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
912 QualType FieldType = (*Field)->getType();
913 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
914 FieldType = Array->getElementType();
915 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
916 const CXXRecordDecl *FieldClassDecl
917 = cast<CXXRecordDecl>(FieldClassType->getDecl());
918 HasConstCopyAssignment
919 = FieldClassDecl->hasConstCopyAssignment(Context);
920 }
921 }
922
923 // Otherwise, the implicitly declared copy assignment operator will
924 // have the form
925 //
926 // X& X::operator=(X&)
927 QualType ArgType = ClassType;
928 QualType RetType = Context.getReferenceType(ArgType);
929 if (HasConstCopyAssignment)
930 ArgType = ArgType.withConst();
931 ArgType = Context.getReferenceType(ArgType);
932
933 // An implicitly-declared copy assignment operator is an inline public
934 // member of its class.
935 DeclarationName Name =
936 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
937 CXXMethodDecl *CopyAssignment =
938 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
939 Context.getFunctionType(RetType, &ArgType, 1,
940 false, 0),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000941 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000942 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000943 CopyAssignment->setImplicit();
Sebastian Redl64b45f72009-01-05 20:52:13 +0000944
945 // Add the parameter to the operator.
946 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
947 ClassDecl->getLocation(),
948 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000949 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000950 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000951
952 // Don't call addedAssignmentOperator. There is no way to distinguish an
953 // implicit from an explicit assignment operator.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000954 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000955 }
956
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000957 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000958 // C++ [class.dtor]p2:
959 // If a class has no user-declared destructor, a destructor is
960 // declared implicitly. An implicitly-declared destructor is an
961 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000962 DeclarationName Name
963 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000964 CXXDestructorDecl *Destructor
965 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000966 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000967 Context.getFunctionType(Context.VoidTy,
968 0, 0, false, 0),
969 /*isInline=*/true,
970 /*isImplicitlyDeclared=*/true);
971 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000972 Destructor->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000973 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000974 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000975}
976
Douglas Gregor72b505b2008-12-16 21:30:33 +0000977/// ActOnStartDelayedCXXMethodDeclaration - We have completed
978/// parsing a top-level (non-nested) C++ class, and we are now
979/// parsing those parts of the given Method declaration that could
980/// not be parsed earlier (C++ [class.mem]p2), such as default
981/// arguments. This action should enter the scope of the given
982/// Method declaration as if we had just parsed the qualified method
983/// name. However, it should not bring the parameters into scope;
984/// that will be performed by ActOnDelayedCXXMethodParameter.
985void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
986 CXXScopeSpec SS;
987 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
988 ActOnCXXEnterDeclaratorScope(S, SS);
989}
990
991/// ActOnDelayedCXXMethodParameter - We've already started a delayed
992/// C++ method declaration. We're (re-)introducing the given
993/// function parameter into scope for use in parsing later parts of
994/// the method declaration. For example, we could see an
995/// ActOnParamDefaultArgument event for this parameter.
996void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
997 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +0000998
999 // If this parameter has an unparsed default argument, clear it out
1000 // to make way for the parsed default argument.
1001 if (Param->hasUnparsedDefaultArg())
1002 Param->setDefaultArg(0);
1003
Douglas Gregor72b505b2008-12-16 21:30:33 +00001004 S->AddDecl(Param);
1005 if (Param->getDeclName())
1006 IdResolver.AddDecl(Param);
1007}
1008
1009/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1010/// processing the delayed method declaration for Method. The method
1011/// declaration is now considered finished. There may be a separate
1012/// ActOnStartOfFunctionDef action later (not necessarily
1013/// immediately!) for this method, if it was also defined inside the
1014/// class body.
1015void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1016 FunctionDecl *Method = (FunctionDecl*)MethodD;
1017 CXXScopeSpec SS;
1018 SS.setScopeRep(Method->getDeclContext());
1019 ActOnCXXExitDeclaratorScope(S, SS);
1020
1021 // Now that we have our default arguments, check the constructor
1022 // again. It could produce additional diagnostics or affect whether
1023 // the class has implicitly-declared destructors, among other
1024 // things.
1025 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1026 if (CheckConstructor(Constructor))
1027 Constructor->setInvalidDecl();
1028 }
1029
1030 // Check the default arguments, which we may have added.
1031 if (!Method->isInvalidDecl())
1032 CheckCXXDefaultArguments(Method);
1033}
1034
Douglas Gregor42a552f2008-11-05 20:51:48 +00001035/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001036/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001037/// R. If there are any errors in the declarator, this routine will
1038/// emit diagnostics and return true. Otherwise, it will return
1039/// false. Either way, the type @p R will be updated to reflect a
1040/// well-formed type for the constructor.
1041bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1042 FunctionDecl::StorageClass& SC) {
1043 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1044 bool isInvalid = false;
1045
1046 // C++ [class.ctor]p3:
1047 // A constructor shall not be virtual (10.3) or static (9.4). A
1048 // constructor can be invoked for a const, volatile or const
1049 // volatile object. A constructor shall not be declared const,
1050 // volatile, or const volatile (9.3.2).
1051 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001052 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1053 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1054 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001055 isInvalid = true;
1056 }
1057 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001058 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1059 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1060 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001061 isInvalid = true;
1062 SC = FunctionDecl::None;
1063 }
1064 if (D.getDeclSpec().hasTypeSpecifier()) {
1065 // Constructors don't have return types, but the parser will
1066 // happily parse something like:
1067 //
1068 // class X {
1069 // float X(float);
1070 // };
1071 //
1072 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001073 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1074 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1075 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001076 }
1077 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1078 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1079 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001080 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1081 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001082 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1084 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001085 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1087 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001088 }
1089
1090 // Rebuild the function type "R" without any type qualifiers (in
1091 // case any of the errors above fired) and with "void" as the
1092 // return type, since constructors don't have return types. We
1093 // *always* have to do this, because GetTypeForDeclarator will
1094 // put in a result type of "int" when none was specified.
1095 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1096 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1097 Proto->getNumArgs(),
1098 Proto->isVariadic(),
1099 0);
1100
1101 return isInvalid;
1102}
1103
Douglas Gregor72b505b2008-12-16 21:30:33 +00001104/// CheckConstructor - Checks a fully-formed constructor for
1105/// well-formedness, issuing any diagnostics required. Returns true if
1106/// the constructor declarator is invalid.
1107bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1108 if (Constructor->isInvalidDecl())
1109 return true;
1110
1111 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1112 bool Invalid = false;
1113
1114 // C++ [class.copy]p3:
1115 // A declaration of a constructor for a class X is ill-formed if
1116 // its first parameter is of type (optionally cv-qualified) X and
1117 // either there are no other parameters or else all other
1118 // parameters have default arguments.
1119 if ((Constructor->getNumParams() == 1) ||
1120 (Constructor->getNumParams() > 1 &&
1121 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1122 QualType ParamType = Constructor->getParamDecl(0)->getType();
1123 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1124 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1125 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1126 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1127 Invalid = true;
1128 }
1129 }
1130
1131 // Notify the class that we've added a constructor.
1132 ClassDecl->addedConstructor(Context, Constructor);
1133
1134 return Invalid;
1135}
1136
Douglas Gregor42a552f2008-11-05 20:51:48 +00001137/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1138/// the well-formednes of the destructor declarator @p D with type @p
1139/// R. If there are any errors in the declarator, this routine will
1140/// emit diagnostics and return true. Otherwise, it will return
1141/// false. Either way, the type @p R will be updated to reflect a
1142/// well-formed type for the destructor.
1143bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1144 FunctionDecl::StorageClass& SC) {
1145 bool isInvalid = false;
1146
1147 // C++ [class.dtor]p1:
1148 // [...] A typedef-name that names a class is a class-name
1149 // (7.1.3); however, a typedef-name that names a class shall not
1150 // be used as the identifier in the declarator for a destructor
1151 // declaration.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001152 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1153 if (DeclaratorType->getAsTypedefType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001154 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001155 << DeclaratorType;
Douglas Gregor55c60952008-11-10 14:41:22 +00001156 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001157 }
1158
1159 // C++ [class.dtor]p2:
1160 // A destructor is used to destroy objects of its class type. A
1161 // destructor takes no parameters, and no return type can be
1162 // specified for it (not even void). The address of a destructor
1163 // shall not be taken. A destructor shall not be static. A
1164 // destructor can be invoked for a const, volatile or const
1165 // volatile object. A destructor shall not be declared const,
1166 // volatile or const volatile (9.3.2).
1167 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001168 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1169 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1170 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001171 isInvalid = true;
1172 SC = FunctionDecl::None;
1173 }
1174 if (D.getDeclSpec().hasTypeSpecifier()) {
1175 // Destructors don't have return types, but the parser will
1176 // happily parse something like:
1177 //
1178 // class X {
1179 // float ~X();
1180 // };
1181 //
1182 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001183 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1184 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1185 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001186 }
1187 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1188 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1189 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001190 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1191 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001192 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001193 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1194 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001195 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001196 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1197 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001198 }
1199
1200 // Make sure we don't have any parameters.
1201 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1202 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1203
1204 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001205 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001206 }
1207
1208 // Make sure the destructor isn't variadic.
1209 if (R->getAsFunctionTypeProto()->isVariadic())
1210 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1211
1212 // Rebuild the function type "R" without any type qualifiers or
1213 // parameters (in case any of the errors above fired) and with
1214 // "void" as the return type, since destructors don't have return
1215 // types. We *always* have to do this, because GetTypeForDeclarator
1216 // will put in a result type of "int" when none was specified.
1217 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1218
1219 return isInvalid;
1220}
1221
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001222/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1223/// well-formednes of the conversion function declarator @p D with
1224/// type @p R. If there are any errors in the declarator, this routine
1225/// will emit diagnostics and return true. Otherwise, it will return
1226/// false. Either way, the type @p R will be updated to reflect a
1227/// well-formed type for the conversion operator.
1228bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1229 FunctionDecl::StorageClass& SC) {
1230 bool isInvalid = false;
1231
1232 // C++ [class.conv.fct]p1:
1233 // Neither parameter types nor return type can be specified. The
1234 // type of a conversion function (8.3.5) is “function taking no
1235 // parameter returning conversion-type-id.”
1236 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001237 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1238 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1239 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001240 isInvalid = true;
1241 SC = FunctionDecl::None;
1242 }
1243 if (D.getDeclSpec().hasTypeSpecifier()) {
1244 // Conversion functions don't have return types, but the parser will
1245 // happily parse something like:
1246 //
1247 // class X {
1248 // float operator bool();
1249 // };
1250 //
1251 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001252 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1253 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1254 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001255 }
1256
1257 // Make sure we don't have any parameters.
1258 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1259 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1260
1261 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001262 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001263 }
1264
1265 // Make sure the conversion function isn't variadic.
1266 if (R->getAsFunctionTypeProto()->isVariadic())
1267 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1268
1269 // C++ [class.conv.fct]p4:
1270 // The conversion-type-id shall not represent a function type nor
1271 // an array type.
1272 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1273 if (ConvType->isArrayType()) {
1274 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1275 ConvType = Context.getPointerType(ConvType);
1276 } else if (ConvType->isFunctionType()) {
1277 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1278 ConvType = Context.getPointerType(ConvType);
1279 }
1280
1281 // Rebuild the function type "R" without any parameters (in case any
1282 // of the errors above fired) and with the conversion type as the
1283 // return type.
1284 R = Context.getFunctionType(ConvType, 0, 0, false,
1285 R->getAsFunctionTypeProto()->getTypeQuals());
1286
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001287 // C++0x explicit conversion operators.
1288 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1289 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1290 diag::warn_explicit_conversion_functions)
1291 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1292
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001293 return isInvalid;
1294}
1295
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001296/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1297/// the declaration of the given C++ conversion function. This routine
1298/// is responsible for recording the conversion function in the C++
1299/// class, if possible.
1300Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1301 assert(Conversion && "Expected to receive a conversion function declaration");
1302
Douglas Gregor9d350972008-12-12 08:25:50 +00001303 // Set the lexical context of this conversion function
1304 Conversion->setLexicalDeclContext(CurContext);
1305
1306 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001307
1308 // Make sure we aren't redeclaring the conversion function.
1309 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001310
1311 // C++ [class.conv.fct]p1:
1312 // [...] A conversion function is never used to convert a
1313 // (possibly cv-qualified) object to the (possibly cv-qualified)
1314 // same object type (or a reference to it), to a (possibly
1315 // cv-qualified) base class of that type (or a reference to it),
1316 // or to (possibly cv-qualified) void.
1317 // FIXME: Suppress this warning if the conversion function ends up
1318 // being a virtual function that overrides a virtual function in a
1319 // base class.
1320 QualType ClassType
1321 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1322 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1323 ConvType = ConvTypeRef->getPointeeType();
1324 if (ConvType->isRecordType()) {
1325 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1326 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001327 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001328 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001329 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001330 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001331 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001332 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001333 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001334 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001335 }
1336
Douglas Gregor70316a02008-12-26 15:00:45 +00001337 if (Conversion->getPreviousDeclaration()) {
1338 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1339 for (OverloadedFunctionDecl::function_iterator
1340 Conv = Conversions->function_begin(),
1341 ConvEnd = Conversions->function_end();
1342 Conv != ConvEnd; ++Conv) {
1343 if (*Conv == Conversion->getPreviousDeclaration()) {
1344 *Conv = Conversion;
1345 return (DeclTy *)Conversion;
1346 }
1347 }
1348 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1349 } else
1350 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001351
1352 return (DeclTy *)Conversion;
1353}
1354
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001355//===----------------------------------------------------------------------===//
1356// Namespace Handling
1357//===----------------------------------------------------------------------===//
1358
1359/// ActOnStartNamespaceDef - This is called at the start of a namespace
1360/// definition.
1361Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1362 SourceLocation IdentLoc,
1363 IdentifierInfo *II,
1364 SourceLocation LBrace) {
1365 NamespaceDecl *Namespc =
1366 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1367 Namespc->setLBracLoc(LBrace);
1368
1369 Scope *DeclRegionScope = NamespcScope->getParent();
1370
1371 if (II) {
1372 // C++ [namespace.def]p2:
1373 // The identifier in an original-namespace-definition shall not have been
1374 // previously defined in the declarative region in which the
1375 // original-namespace-definition appears. The identifier in an
1376 // original-namespace-definition is the name of the namespace. Subsequently
1377 // in that declarative region, it is treated as an original-namespace-name.
1378
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001379 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1380 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001381
1382 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1383 // This is an extended namespace definition.
1384 // Attach this namespace decl to the chain of extended namespace
1385 // definitions.
1386 OrigNS->setNextNamespace(Namespc);
1387 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001388
Douglas Gregor44b43212008-12-11 16:49:14 +00001389 // Remove the previous declaration from the scope.
1390 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001391 IdResolver.RemoveDecl(OrigNS);
1392 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001393 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001394 } else if (PrevDecl) {
1395 // This is an invalid name redefinition.
1396 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1397 << Namespc->getDeclName();
1398 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1399 Namespc->setInvalidDecl();
1400 // Continue on to push Namespc as current DeclContext and return it.
1401 }
1402
1403 PushOnScopeChains(Namespc, DeclRegionScope);
1404 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001405 // FIXME: Handle anonymous namespaces
1406 }
1407
1408 // Although we could have an invalid decl (i.e. the namespace name is a
1409 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001410 // FIXME: We should be able to push Namespc here, so that the
1411 // each DeclContext for the namespace has the declarations
1412 // that showed up in that particular namespace definition.
1413 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001414 return Namespc;
1415}
1416
1417/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1418/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1419void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1420 Decl *Dcl = static_cast<Decl *>(D);
1421 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1422 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1423 Namespc->setRBracLoc(RBrace);
1424 PopDeclContext();
1425}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001426
Douglas Gregorf780abc2008-12-30 03:27:21 +00001427Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1428 SourceLocation UsingLoc,
1429 SourceLocation NamespcLoc,
1430 const CXXScopeSpec &SS,
1431 SourceLocation IdentLoc,
1432 IdentifierInfo *NamespcName,
1433 AttributeList *AttrList) {
1434 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1435 assert(NamespcName && "Invalid NamespcName.");
1436 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001437 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00001438
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001439 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00001440
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001441 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001442 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1443 LookupNamespaceName, false);
1444 if (R.isAmbiguous()) {
1445 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1446 return 0;
1447 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001448 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001449 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001450 // C++ [namespace.udir]p1:
1451 // A using-directive specifies that the names in the nominated
1452 // namespace can be used in the scope in which the
1453 // using-directive appears after the using-directive. During
1454 // unqualified name lookup (3.4.1), the names appear as if they
1455 // were declared in the nearest enclosing namespace which
1456 // contains both the using-directive and the nominated
1457 // namespace. [Note: in this context, “contains” means “contains
1458 // directly or indirectly”. ]
1459
1460 // Find enclosing context containing both using-directive and
1461 // nominated namespace.
1462 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1463 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1464 CommonAncestor = CommonAncestor->getParent();
1465
1466 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1467 NamespcLoc, IdentLoc,
1468 cast<NamespaceDecl>(NS),
1469 CommonAncestor);
1470 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001471 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001472 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001473 }
1474
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001475 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001476 delete AttrList;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001477 return UDir;
1478}
1479
1480void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1481 // If scope has associated entity, then using directive is at namespace
1482 // or translation unit scope. We add UsingDirectiveDecls, into
1483 // it's lookup structure.
1484 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1485 Ctx->addDecl(UDir);
1486 else
1487 // Otherwise it is block-sope. using-directives will affect lookup
1488 // only to the end of scope.
1489 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001490}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001491
1492/// AddCXXDirectInitializerToDecl - This action is called immediately after
1493/// ActOnDeclarator, when a C++ direct initializer is present.
1494/// e.g: "int x(1);"
1495void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1496 ExprTy **ExprTys, unsigned NumExprs,
1497 SourceLocation *CommaLocs,
1498 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001499 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001500 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001501
1502 // If there is no declaration, there was an error parsing it. Just ignore
1503 // the initializer.
1504 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001505 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek8189cde2009-02-07 01:47:29 +00001506 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001507 return;
1508 }
1509
1510 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1511 if (!VDecl) {
1512 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1513 RealDecl->setInvalidDecl();
1514 return;
1515 }
1516
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001517 // We will treat direct-initialization as a copy-initialization:
1518 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001519 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1520 //
1521 // Clients that want to distinguish between the two forms, can check for
1522 // direct initializer using VarDecl::hasCXXDirectInitializer().
1523 // A major benefit is that clients that don't particularly care about which
1524 // exactly form was it (like the CodeGen) can handle both cases without
1525 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001526
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001527 // C++ 8.5p11:
1528 // The form of initialization (using parentheses or '=') is generally
1529 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001530 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001531 QualType DeclInitType = VDecl->getType();
1532 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1533 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001534
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001535 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001536 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001537 = PerformInitializationByConstructor(DeclInitType,
1538 (Expr **)ExprTys, NumExprs,
1539 VDecl->getLocation(),
1540 SourceRange(VDecl->getLocation(),
1541 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001542 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001543 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001544 if (!Constructor) {
1545 RealDecl->setInvalidDecl();
1546 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001547
1548 // Let clients know that initialization was done with a direct
1549 // initializer.
1550 VDecl->setCXXDirectInitializer(true);
1551
1552 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1553 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001554 return;
1555 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001556
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001557 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001558 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1559 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001560 RealDecl->setInvalidDecl();
1561 return;
1562 }
1563
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001564 // Let clients know that initialization was done with a direct initializer.
1565 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001566
1567 assert(NumExprs == 1 && "Expected 1 expression");
1568 // Set the init expression, handles conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001569 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001570}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001571
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001572/// PerformInitializationByConstructor - Perform initialization by
1573/// constructor (C++ [dcl.init]p14), which may occur as part of
1574/// direct-initialization or copy-initialization. We are initializing
1575/// an object of type @p ClassType with the given arguments @p
1576/// Args. @p Loc is the location in the source code where the
1577/// initializer occurs (e.g., a declaration, member initializer,
1578/// functional cast, etc.) while @p Range covers the whole
1579/// initialization. @p InitEntity is the entity being initialized,
1580/// which may by the name of a declaration or a type. @p Kind is the
1581/// kind of initialization we're performing, which affects whether
1582/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001583/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001584/// when the initialization fails, emits a diagnostic and returns
1585/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001586CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001587Sema::PerformInitializationByConstructor(QualType ClassType,
1588 Expr **Args, unsigned NumArgs,
1589 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001590 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001591 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001592 const RecordType *ClassRec = ClassType->getAsRecordType();
1593 assert(ClassRec && "Can only initialize a class type here");
1594
1595 // C++ [dcl.init]p14:
1596 //
1597 // If the initialization is direct-initialization, or if it is
1598 // copy-initialization where the cv-unqualified version of the
1599 // source type is the same class as, or a derived class of, the
1600 // class of the destination, constructors are considered. The
1601 // applicable constructors are enumerated (13.3.1.3), and the
1602 // best one is chosen through overload resolution (13.3). The
1603 // constructor so selected is called to initialize the object,
1604 // with the initializer expression(s) as its argument(s). If no
1605 // constructor applies, or the overload resolution is ambiguous,
1606 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001607 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1608 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001609
1610 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001611 DeclarationName ConstructorName
1612 = Context.DeclarationNames.getCXXConstructorName(
1613 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001614 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001615 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001616 Con != ConEnd; ++Con) {
1617 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001618 if ((Kind == IK_Direct) ||
1619 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1620 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1621 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1622 }
1623
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001624 // FIXME: When we decide not to synthesize the implicitly-declared
1625 // constructors, we'll need to make them appear here.
1626
Douglas Gregor18fe5682008-11-03 20:45:27 +00001627 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001628 switch (BestViableFunction(CandidateSet, Best)) {
1629 case OR_Success:
1630 // We found a constructor. Return it.
1631 return cast<CXXConstructorDecl>(Best->Function);
1632
1633 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001634 if (InitEntity)
1635 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1636 << InitEntity << (unsigned)CandidateSet.size() << Range;
1637 else
1638 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1639 << ClassType << (unsigned)CandidateSet.size() << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00001640 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001641 return 0;
1642
1643 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001644 if (InitEntity)
1645 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1646 else
1647 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001648 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1649 return 0;
1650 }
1651
1652 return 0;
1653}
1654
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001655/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1656/// determine whether they are reference-related,
1657/// reference-compatible, reference-compatible with added
1658/// qualification, or incompatible, for use in C++ initialization by
1659/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1660/// type, and the first type (T1) is the pointee type of the reference
1661/// type being initialized.
1662Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001663Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1664 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001665 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1666 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1667
1668 T1 = Context.getCanonicalType(T1);
1669 T2 = Context.getCanonicalType(T2);
1670 QualType UnqualT1 = T1.getUnqualifiedType();
1671 QualType UnqualT2 = T2.getUnqualifiedType();
1672
1673 // C++ [dcl.init.ref]p4:
1674 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1675 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1676 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001677 if (UnqualT1 == UnqualT2)
1678 DerivedToBase = false;
1679 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1680 DerivedToBase = true;
1681 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001682 return Ref_Incompatible;
1683
1684 // At this point, we know that T1 and T2 are reference-related (at
1685 // least).
1686
1687 // C++ [dcl.init.ref]p4:
1688 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1689 // reference-related to T2 and cv1 is the same cv-qualification
1690 // as, or greater cv-qualification than, cv2. For purposes of
1691 // overload resolution, cases for which cv1 is greater
1692 // cv-qualification than cv2 are identified as
1693 // reference-compatible with added qualification (see 13.3.3.2).
1694 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1695 return Ref_Compatible;
1696 else if (T1.isMoreQualifiedThan(T2))
1697 return Ref_Compatible_With_Added_Qualification;
1698 else
1699 return Ref_Related;
1700}
1701
1702/// CheckReferenceInit - Check the initialization of a reference
1703/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1704/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001705/// list), and DeclType is the type of the declaration. When ICS is
1706/// non-null, this routine will compute the implicit conversion
1707/// sequence according to C++ [over.ics.ref] and will not produce any
1708/// diagnostics; when ICS is null, it will emit diagnostics when any
1709/// errors are found. Either way, a return value of true indicates
1710/// that there was a failure, a return value of false indicates that
1711/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001712///
1713/// When @p SuppressUserConversions, user-defined conversions are
1714/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001715/// When @p AllowExplicit, we also permit explicit user-defined
1716/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001717bool
1718Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001719 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001720 bool SuppressUserConversions,
1721 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001722 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1723
1724 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1725 QualType T2 = Init->getType();
1726
Douglas Gregor904eed32008-11-10 20:40:00 +00001727 // If the initializer is the address of an overloaded function, try
1728 // to resolve the overloaded function. If all goes well, T2 is the
1729 // type of the resulting function.
1730 if (T2->isOverloadType()) {
1731 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1732 ICS != 0);
1733 if (Fn) {
1734 // Since we're performing this reference-initialization for
1735 // real, update the initializer with the resulting function.
1736 if (!ICS)
1737 FixOverloadedFunctionReference(Init, Fn);
1738
1739 T2 = Fn->getType();
1740 }
1741 }
1742
Douglas Gregor15da57e2008-10-29 02:00:59 +00001743 // Compute some basic properties of the types and the initializer.
1744 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001745 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001746 ReferenceCompareResult RefRelationship
1747 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1748
1749 // Most paths end in a failed conversion.
1750 if (ICS)
1751 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001752
1753 // C++ [dcl.init.ref]p5:
1754 // A reference to type “cv1 T1” is initialized by an expression
1755 // of type “cv2 T2” as follows:
1756
1757 // -- If the initializer expression
1758
1759 bool BindsDirectly = false;
1760 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1761 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001762 //
1763 // Note that the bit-field check is skipped if we are just computing
1764 // the implicit conversion sequence (C++ [over.best.ics]p2).
1765 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1766 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001767 BindsDirectly = true;
1768
Douglas Gregor15da57e2008-10-29 02:00:59 +00001769 if (ICS) {
1770 // C++ [over.ics.ref]p1:
1771 // When a parameter of reference type binds directly (8.5.3)
1772 // to an argument expression, the implicit conversion sequence
1773 // is the identity conversion, unless the argument expression
1774 // has a type that is a derived class of the parameter type,
1775 // in which case the implicit conversion sequence is a
1776 // derived-to-base Conversion (13.3.3.1).
1777 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1778 ICS->Standard.First = ICK_Identity;
1779 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1780 ICS->Standard.Third = ICK_Identity;
1781 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1782 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001783 ICS->Standard.ReferenceBinding = true;
1784 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001785
1786 // Nothing more to do: the inaccessibility/ambiguity check for
1787 // derived-to-base conversions is suppressed when we're
1788 // computing the implicit conversion sequence (C++
1789 // [over.best.ics]p2).
1790 return false;
1791 } else {
1792 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001793 // FIXME: Binding to a subobject of the lvalue is going to require
1794 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001795 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001796 }
1797 }
1798
1799 // -- has a class type (i.e., T2 is a class type) and can be
1800 // implicitly converted to an lvalue of type “cv3 T3,”
1801 // where “cv1 T1” is reference-compatible with “cv3 T3”
1802 // 92) (this conversion is selected by enumerating the
1803 // applicable conversion functions (13.3.1.6) and choosing
1804 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001805 if (!SuppressUserConversions && T2->isRecordType()) {
1806 // FIXME: Look for conversions in base classes!
1807 CXXRecordDecl *T2RecordDecl
1808 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001809
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001810 OverloadCandidateSet CandidateSet;
1811 OverloadedFunctionDecl *Conversions
1812 = T2RecordDecl->getConversionFunctions();
1813 for (OverloadedFunctionDecl::function_iterator Func
1814 = Conversions->function_begin();
1815 Func != Conversions->function_end(); ++Func) {
1816 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1817
1818 // If the conversion function doesn't return a reference type,
1819 // it can't be considered for this conversion.
1820 // FIXME: This will change when we support rvalue references.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001821 if (Conv->getConversionType()->isReferenceType() &&
1822 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001823 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1824 }
1825
1826 OverloadCandidateSet::iterator Best;
1827 switch (BestViableFunction(CandidateSet, Best)) {
1828 case OR_Success:
1829 // This is a direct binding.
1830 BindsDirectly = true;
1831
1832 if (ICS) {
1833 // C++ [over.ics.ref]p1:
1834 //
1835 // [...] If the parameter binds directly to the result of
1836 // applying a conversion function to the argument
1837 // expression, the implicit conversion sequence is a
1838 // user-defined conversion sequence (13.3.3.1.2), with the
1839 // second standard conversion sequence either an identity
1840 // conversion or, if the conversion function returns an
1841 // entity of a type that is a derived class of the parameter
1842 // type, a derived-to-base Conversion.
1843 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1844 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1845 ICS->UserDefined.After = Best->FinalConversion;
1846 ICS->UserDefined.ConversionFunction = Best->Function;
1847 assert(ICS->UserDefined.After.ReferenceBinding &&
1848 ICS->UserDefined.After.DirectBinding &&
1849 "Expected a direct reference binding!");
1850 return false;
1851 } else {
1852 // Perform the conversion.
1853 // FIXME: Binding to a subobject of the lvalue is going to require
1854 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001855 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001856 }
1857 break;
1858
1859 case OR_Ambiguous:
1860 assert(false && "Ambiguous reference binding conversions not implemented.");
1861 return true;
1862
1863 case OR_No_Viable_Function:
1864 // There was no suitable conversion; continue with other checks.
1865 break;
1866 }
1867 }
1868
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001869 if (BindsDirectly) {
1870 // C++ [dcl.init.ref]p4:
1871 // [...] In all cases where the reference-related or
1872 // reference-compatible relationship of two types is used to
1873 // establish the validity of a reference binding, and T1 is a
1874 // base class of T2, a program that necessitates such a binding
1875 // is ill-formed if T1 is an inaccessible (clause 11) or
1876 // ambiguous (10.2) base class of T2.
1877 //
1878 // Note that we only check this condition when we're allowed to
1879 // complain about errors, because we should not be checking for
1880 // ambiguity (or inaccessibility) unless the reference binding
1881 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001882 if (DerivedToBase)
1883 return CheckDerivedToBaseConversion(T2, T1,
1884 Init->getSourceRange().getBegin(),
1885 Init->getSourceRange());
1886 else
1887 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001888 }
1889
1890 // -- Otherwise, the reference shall be to a non-volatile const
1891 // type (i.e., cv1 shall be const).
1892 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001893 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001894 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001895 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001896 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1897 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001898 return true;
1899 }
1900
1901 // -- If the initializer expression is an rvalue, with T2 a
1902 // class type, and “cv1 T1” is reference-compatible with
1903 // “cv2 T2,” the reference is bound in one of the
1904 // following ways (the choice is implementation-defined):
1905 //
1906 // -- The reference is bound to the object represented by
1907 // the rvalue (see 3.10) or to a sub-object within that
1908 // object.
1909 //
1910 // -- A temporary of type “cv1 T2” [sic] is created, and
1911 // a constructor is called to copy the entire rvalue
1912 // object into the temporary. The reference is bound to
1913 // the temporary or to a sub-object within the
1914 // temporary.
1915 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001916 // The constructor that would be used to make the copy
1917 // shall be callable whether or not the copy is actually
1918 // done.
1919 //
1920 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1921 // freedom, so we will always take the first option and never build
1922 // a temporary in this case. FIXME: We will, however, have to check
1923 // for the presence of a copy constructor in C++98/03 mode.
1924 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001925 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1926 if (ICS) {
1927 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1928 ICS->Standard.First = ICK_Identity;
1929 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1930 ICS->Standard.Third = ICK_Identity;
1931 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1932 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001933 ICS->Standard.ReferenceBinding = true;
1934 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001935 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001936 // FIXME: Binding to a subobject of the rvalue is going to require
1937 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001938 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001939 }
1940 return false;
1941 }
1942
1943 // -- Otherwise, a temporary of type “cv1 T1” is created and
1944 // initialized from the initializer expression using the
1945 // rules for a non-reference copy initialization (8.5). The
1946 // reference is then bound to the temporary. If T1 is
1947 // reference-related to T2, cv1 must be the same
1948 // cv-qualification as, or greater cv-qualification than,
1949 // cv2; otherwise, the program is ill-formed.
1950 if (RefRelationship == Ref_Related) {
1951 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1952 // we would be reference-compatible or reference-compatible with
1953 // added qualification. But that wasn't the case, so the reference
1954 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001955 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001956 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001957 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001958 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1959 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001960 return true;
1961 }
1962
Douglas Gregor734d9862009-01-30 23:27:23 +00001963 // If at least one of the types is a class type, the types are not
1964 // related, and we aren't allowed any user conversions, the
1965 // reference binding fails. This case is important for breaking
1966 // recursion, since TryImplicitConversion below will attempt to
1967 // create a temporary through the use of a copy constructor.
1968 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
1969 (T1->isRecordType() || T2->isRecordType())) {
1970 if (!ICS)
1971 Diag(Init->getSourceRange().getBegin(),
1972 diag::err_typecheck_convert_incompatible)
1973 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
1974 return true;
1975 }
1976
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001977 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001978 if (ICS) {
1979 /// C++ [over.ics.ref]p2:
1980 ///
1981 /// When a parameter of reference type is not bound directly to
1982 /// an argument expression, the conversion sequence is the one
1983 /// required to convert the argument expression to the
1984 /// underlying type of the reference according to
1985 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1986 /// to copy-initializing a temporary of the underlying type with
1987 /// the argument expression. Any difference in top-level
1988 /// cv-qualification is subsumed by the initialization itself
1989 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001990 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001991 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1992 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00001993 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00001994 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001995}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001996
1997/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1998/// of this overloaded operator is well-formed. If so, returns false;
1999/// otherwise, emits appropriate diagnostics and returns true.
2000bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002001 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002002 "Expected an overloaded operator declaration");
2003
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002004 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2005
2006 // C++ [over.oper]p5:
2007 // The allocation and deallocation functions, operator new,
2008 // operator new[], operator delete and operator delete[], are
2009 // described completely in 3.7.3. The attributes and restrictions
2010 // found in the rest of this subclause do not apply to them unless
2011 // explicitly stated in 3.7.3.
2012 // FIXME: Write a separate routine for checking this. For now, just
2013 // allow it.
2014 if (Op == OO_New || Op == OO_Array_New ||
2015 Op == OO_Delete || Op == OO_Array_Delete)
2016 return false;
2017
2018 // C++ [over.oper]p6:
2019 // An operator function shall either be a non-static member
2020 // function or be a non-member function and have at least one
2021 // parameter whose type is a class, a reference to a class, an
2022 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002023 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2024 if (MethodDecl->isStatic())
2025 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002026 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002027 } else {
2028 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002029 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2030 ParamEnd = FnDecl->param_end();
2031 Param != ParamEnd; ++Param) {
2032 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002033 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2034 ClassOrEnumParam = true;
2035 break;
2036 }
2037 }
2038
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002039 if (!ClassOrEnumParam)
2040 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002041 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002042 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002043 }
2044
2045 // C++ [over.oper]p8:
2046 // An operator function cannot have default arguments (8.3.6),
2047 // except where explicitly stated below.
2048 //
2049 // Only the function-call operator allows default arguments
2050 // (C++ [over.call]p1).
2051 if (Op != OO_Call) {
2052 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2053 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002054 if ((*Param)->hasUnparsedDefaultArg())
2055 return Diag((*Param)->getLocation(),
2056 diag::err_operator_overload_default_arg)
2057 << FnDecl->getDeclName();
2058 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002059 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002060 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002061 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002062 }
2063 }
2064
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002065 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2066 { false, false, false }
2067#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2068 , { Unary, Binary, MemberOnly }
2069#include "clang/Basic/OperatorKinds.def"
2070 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002071
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002072 bool CanBeUnaryOperator = OperatorUses[Op][0];
2073 bool CanBeBinaryOperator = OperatorUses[Op][1];
2074 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002075
2076 // C++ [over.oper]p8:
2077 // [...] Operator functions cannot have more or fewer parameters
2078 // than the number required for the corresponding operator, as
2079 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002080 unsigned NumParams = FnDecl->getNumParams()
2081 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002082 if (Op != OO_Call &&
2083 ((NumParams == 1 && !CanBeUnaryOperator) ||
2084 (NumParams == 2 && !CanBeBinaryOperator) ||
2085 (NumParams < 1) || (NumParams > 2))) {
2086 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002087 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002088 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002089 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002090 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002091 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002092 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002093 assert(CanBeBinaryOperator &&
2094 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002095 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002096 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002097
Chris Lattner416e46f2008-11-21 07:57:12 +00002098 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002099 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002100 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002101
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002102 // Overloaded operators other than operator() cannot be variadic.
2103 if (Op != OO_Call &&
2104 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002105 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002106 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002107 }
2108
2109 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002110 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2111 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002112 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002113 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002114 }
2115
2116 // C++ [over.inc]p1:
2117 // The user-defined function called operator++ implements the
2118 // prefix and postfix ++ operator. If this function is a member
2119 // function with no parameters, or a non-member function with one
2120 // parameter of class or enumeration type, it defines the prefix
2121 // increment operator ++ for objects of that type. If the function
2122 // is a member function with one parameter (which shall be of type
2123 // int) or a non-member function with two parameters (the second
2124 // of which shall be of type int), it defines the postfix
2125 // increment operator ++ for objects of that type.
2126 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2127 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2128 bool ParamIsInt = false;
2129 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2130 ParamIsInt = BT->getKind() == BuiltinType::Int;
2131
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002132 if (!ParamIsInt)
2133 return Diag(LastParam->getLocation(),
2134 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002135 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002136 }
2137
Sebastian Redl64b45f72009-01-05 20:52:13 +00002138 // Notify the class if it got an assignment operator.
2139 if (Op == OO_Equal) {
2140 // Would have returned earlier otherwise.
2141 assert(isa<CXXMethodDecl>(FnDecl) &&
2142 "Overloaded = not member, but not filtered.");
2143 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2144 Method->getParent()->addedAssignmentOperator(Context, Method);
2145 }
2146
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002147 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002148}
Chris Lattner5a003a42008-12-17 07:09:26 +00002149
Douglas Gregor074149e2009-01-05 19:45:36 +00002150/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2151/// linkage specification, including the language and (if present)
2152/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2153/// the location of the language string literal, which is provided
2154/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2155/// the '{' brace. Otherwise, this linkage specification does not
2156/// have any braces.
2157Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2158 SourceLocation ExternLoc,
2159 SourceLocation LangLoc,
2160 const char *Lang,
2161 unsigned StrSize,
2162 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002163 LinkageSpecDecl::LanguageIDs Language;
2164 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2165 Language = LinkageSpecDecl::lang_c;
2166 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2167 Language = LinkageSpecDecl::lang_cxx;
2168 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002169 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002170 return 0;
2171 }
2172
2173 // FIXME: Add all the various semantics of linkage specifications
2174
Douglas Gregor074149e2009-01-05 19:45:36 +00002175 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2176 LangLoc, Language,
2177 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002178 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002179 PushDeclContext(S, D);
2180 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002181}
2182
Douglas Gregor074149e2009-01-05 19:45:36 +00002183/// ActOnFinishLinkageSpecification - Completely the definition of
2184/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2185/// valid, it's the position of the closing '}' brace in a linkage
2186/// specification that uses braces.
2187Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2188 DeclTy *LinkageSpec,
2189 SourceLocation RBraceLoc) {
2190 if (LinkageSpec)
2191 PopDeclContext();
2192 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002193}
2194
Sebastian Redl4b07b292008-12-22 19:15:10 +00002195/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2196/// handler.
2197Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2198{
2199 QualType ExDeclType = GetTypeForDeclarator(D, S);
2200 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2201
2202 bool Invalid = false;
2203
2204 // Arrays and functions decay.
2205 if (ExDeclType->isArrayType())
2206 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2207 else if (ExDeclType->isFunctionType())
2208 ExDeclType = Context.getPointerType(ExDeclType);
2209
2210 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2211 // The exception-declaration shall not denote a pointer or reference to an
2212 // incomplete type, other than [cv] void*.
2213 QualType BaseType = ExDeclType;
2214 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002215 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002216 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2217 BaseType = Ptr->getPointeeType();
2218 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002219 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002220 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2221 BaseType = Ref->getPointeeType();
2222 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002223 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002224 }
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002225 if ((Mode == 0 || !BaseType->isVoidType()) &&
2226 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00002227 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002228
Sebastian Redl8351da02008-12-22 21:35:02 +00002229 // FIXME: Need to test for ability to copy-construct and destroy the
2230 // exception variable.
2231 // FIXME: Need to check for abstract classes.
2232
Sebastian Redl4b07b292008-12-22 19:15:10 +00002233 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002234 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002235 // The scope should be freshly made just for us. There is just no way
2236 // it contains any previous declaration.
2237 assert(!S->isDeclScope(PrevDecl));
2238 if (PrevDecl->isTemplateParameter()) {
2239 // Maybe we will complain about the shadowed template parameter.
2240 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2241
2242 }
2243 }
2244
2245 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002246 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002247 if (D.getInvalidType() || Invalid)
2248 ExDecl->setInvalidDecl();
2249
2250 if (D.getCXXScopeSpec().isSet()) {
2251 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2252 << D.getCXXScopeSpec().getRange();
2253 ExDecl->setInvalidDecl();
2254 }
2255
2256 // Add the exception declaration into this scope.
2257 S->AddDecl(ExDecl);
2258 if (II)
2259 IdResolver.AddDecl(ExDecl);
2260
2261 ProcessDeclAttributes(ExDecl, D);
2262 return ExDecl;
2263}