blob: 14a481eb715f68c0ad1dc6bdc754057a3aa29657 [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"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000026#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner8123a952008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattner9e979552008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000044
Chris Lattner9e979552008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000052 };
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000061 }
62
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000088 }
Chris Lattner8123a952008-04-10 02:22:51 +000089
Douglas Gregor3996f232008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattner9e979552008-04-12 23:52:44 +000092
Douglas Gregor796da182008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102}
103
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000107void
108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
109 ExprTy *defarg) {
110 ParmVarDecl *Param = (ParmVarDecl *)param;
111 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
112 QualType ParamType = Param->getType();
113
114 // Default arguments are only permitted in C++
115 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 Diag(EqualLoc, diag::err_param_default_argument)
117 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000118 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000119 return;
120 }
121
122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Chris Lattner3d1cee32008-04-08 05:04:30 +0000128 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor61366e92008-12-24 00:01:03 +0000129 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
130 EqualLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000131 Param->getDeclName(),
132 /*DirectInit=*/false);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000133 if (DefaultArgPtr != DefaultArg.get()) {
134 DefaultArg.take();
135 DefaultArg.reset(DefaultArgPtr);
136 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000137 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000138 return;
139 }
140
Chris Lattner8123a952008-04-10 02:22:51 +0000141 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000142 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000143 if (DefaultArgChecker.Visit(DefaultArg.get())) {
144 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000145 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147
Chris Lattner3d1cee32008-04-08 05:04:30 +0000148 // Okay: add the default argument to the parameter
149 Param->setDefaultArg(DefaultArg.take());
150}
151
Douglas Gregor61366e92008-12-24 00:01:03 +0000152/// ActOnParamUnparsedDefaultArgument - We've seen a default
153/// argument for a function parameter, but we can't parse it yet
154/// because we're inside a class definition. Note that this default
155/// argument will be parsed later.
156void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
157 SourceLocation EqualLoc) {
158 ParmVarDecl *Param = (ParmVarDecl*)param;
159 if (Param)
160 Param->setUnparsedDefaultArg();
161}
162
Douglas Gregor72b505b2008-12-16 21:30:33 +0000163/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
164/// the default argument for the parameter param failed.
165void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
166 ((ParmVarDecl*)param)->setInvalidDecl();
167}
168
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000169/// CheckExtraCXXDefaultArguments - Check for any extra default
170/// arguments in the declarator, which is not a function declaration
171/// or definition and therefore is not permitted to have default
172/// arguments. This routine should be invoked for every declarator
173/// that is not a function declaration or definition.
174void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
175 // C++ [dcl.fct.default]p3
176 // A default argument expression shall be specified only in the
177 // parameter-declaration-clause of a function declaration or in a
178 // template-parameter (14.1). It shall not be specified for a
179 // parameter pack. If it is specified in a
180 // parameter-declaration-clause, it shall not occur within a
181 // declarator or abstract-declarator of a parameter-declaration.
182 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
183 DeclaratorChunk &chunk = D.getTypeObject(i);
184 if (chunk.Kind == DeclaratorChunk::Function) {
185 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
186 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187 if (Param->hasUnparsedDefaultArg()) {
188 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
190 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
191 delete Toks;
192 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000193 } else if (Param->getDefaultArg()) {
194 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
195 << Param->getDefaultArg()->getSourceRange();
196 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000197 }
198 }
199 }
200 }
201}
202
Chris Lattner3d1cee32008-04-08 05:04:30 +0000203// MergeCXXFunctionDecl - Merge two declarations of the same C++
204// function, once we already know that they have the same
205// type. Subroutine of MergeFunctionDecl.
206FunctionDecl *
207Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
208 // C++ [dcl.fct.default]p4:
209 //
210 // For non-template functions, default arguments can be added in
211 // later declarations of a function in the same
212 // scope. Declarations in different scopes have completely
213 // distinct sets of default arguments. That is, declarations in
214 // inner scopes do not acquire default arguments from
215 // declarations in outer scopes, and vice versa. In a given
216 // function declaration, all parameters subsequent to a
217 // parameter with a default argument shall have default
218 // arguments supplied in this or previous declarations. A
219 // default argument shall not be redefined by a later
220 // declaration (not even to the same value).
221 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
222 ParmVarDecl *OldParam = Old->getParamDecl(p);
223 ParmVarDecl *NewParam = New->getParamDecl(p);
224
225 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
226 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000227 diag::err_param_default_argument_redefinition)
228 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000229 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000230 } else if (OldParam->getDefaultArg()) {
231 // Merge the old default argument into the new parameter
232 NewParam->setDefaultArg(OldParam->getDefaultArg());
233 }
234 }
235
236 return New;
237}
238
239/// CheckCXXDefaultArguments - Verify that the default arguments for a
240/// function declaration are well-formed according to C++
241/// [dcl.fct.default].
242void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
243 unsigned NumParams = FD->getNumParams();
244 unsigned p;
245
246 // Find first parameter with a default argument
247 for (p = 0; p < NumParams; ++p) {
248 ParmVarDecl *Param = FD->getParamDecl(p);
249 if (Param->getDefaultArg())
250 break;
251 }
252
253 // C++ [dcl.fct.default]p4:
254 // In a given function declaration, all parameters
255 // subsequent to a parameter with a default argument shall
256 // have default arguments supplied in this or previous
257 // declarations. A default argument shall not be redefined
258 // by a later declaration (not even to the same value).
259 unsigned LastMissingDefaultArg = 0;
260 for(; p < NumParams; ++p) {
261 ParmVarDecl *Param = FD->getParamDecl(p);
262 if (!Param->getDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000263 if (Param->isInvalidDecl())
264 /* We already complained about this parameter. */;
265 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000266 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000267 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000268 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000269 else
270 Diag(Param->getLocation(),
271 diag::err_param_default_argument_missing);
272
273 LastMissingDefaultArg = p;
274 }
275 }
276
277 if (LastMissingDefaultArg > 0) {
278 // Some default arguments were missing. Clear out all of the
279 // default arguments up to (and including) the last missing
280 // default argument, so that we leave the function parameters
281 // in a semantically valid state.
282 for (p = 0; p <= LastMissingDefaultArg; ++p) {
283 ParmVarDecl *Param = FD->getParamDecl(p);
284 if (Param->getDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000285 if (!Param->hasUnparsedDefaultArg())
286 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 Param->setDefaultArg(0);
288 }
289 }
290 }
291}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000292
Douglas Gregorb48fe382008-10-31 09:07:45 +0000293/// isCurrentClassName - Determine whether the identifier II is the
294/// name of the class type currently being defined. In the case of
295/// nested classes, this will only return true if II is the name of
296/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000297bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
298 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000299 CXXRecordDecl *CurDecl;
300 if (SS) {
301 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
302 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
303 } else
304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
305
306 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000307 return &II == CurDecl->getIdentifier();
308 else
309 return false;
310}
311
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000312/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
313/// one entry in the base class list of a class specifier, for
314/// example:
315/// class foo : public bar, virtual private baz {
316/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000317Sema::BaseResult
318Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
319 bool Virtual, AccessSpecifier Access,
320 TypeTy *basetype, SourceLocation BaseLoc) {
Sebastian Redl64b45f72009-01-05 20:52:13 +0000321 CXXRecordDecl *Decl = (CXXRecordDecl*)classdecl;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000322 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
323
324 // Base specifiers must be record types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000325 if (!BaseType->isRecordType())
326 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000327
328 // C++ [class.union]p1:
329 // A union shall not be used as a base class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000330 if (BaseType->isUnionType())
331 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000332
333 // C++ [class.union]p1:
334 // A union shall not have base classes.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000335 if (Decl->isUnion())
336 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
337 << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000338
339 // C++ [class.derived]p2:
340 // The class-name in a base-specifier shall not be an incompletely
341 // defined class.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000342 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
343 SpecifierRange))
344 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000345
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000346 // If the base class is polymorphic, the new one is, too.
347 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
348 assert(BaseDecl && "Record type has no declaration");
349 BaseDecl = BaseDecl->getDefinition(Context);
350 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000351 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl64b45f72009-01-05 20:52:13 +0000352 Decl->setPolymorphic(true);
353
354 // C++ [dcl.init.aggr]p1:
355 // An aggregate is [...] a class with [...] no base classes [...].
356 Decl->setAggregate(false);
357 Decl->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000358
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000359 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000360 return new CXXBaseSpecifier(SpecifierRange, Virtual,
361 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000362}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000363
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000364/// ActOnBaseSpecifiers - Attach the given base specifiers to the
365/// class, after checking whether there are any duplicate base
366/// classes.
367void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
368 unsigned NumBases) {
369 if (NumBases == 0)
370 return;
371
372 // Used to keep track of which base types we have already seen, so
373 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000374 // that the key is always the unqualified canonical type of the base
375 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000376 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
377
378 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000379 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
380 unsigned NumGoodBases = 0;
381 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000382 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000383 = Context.getCanonicalType(BaseSpecs[idx]->getType());
384 NewBaseType = NewBaseType.getUnqualifiedType();
385
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000386 if (KnownBaseTypes[NewBaseType]) {
387 // C++ [class.mi]p3:
388 // A class shall not be specified as a direct base class of a
389 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000390 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000391 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000392 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000394
395 // Delete the duplicate base class specifier; we're going to
396 // overwrite its pointer later.
397 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000398 } else {
399 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000400 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
401 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000402 }
403 }
404
405 // Attach the remaining base class specifiers to the derived class.
406 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000407 Decl->setBases(BaseSpecs, NumGoodBases);
408
409 // Delete the remaining (good) base class specifiers, since their
410 // data has been copied into the CXXRecordDecl.
411 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
412 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000413}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000414
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000415//===----------------------------------------------------------------------===//
416// C++ class member Handling
417//===----------------------------------------------------------------------===//
418
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000419/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
420/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
421/// bitfield width if there is one and 'InitExpr' specifies the initializer if
422/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
423/// declarators on it.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000424Sema::DeclTy *
425Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
426 ExprTy *BW, ExprTy *InitExpr,
427 DeclTy *LastInGroup) {
428 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000429 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000430 Expr *BitWidth = static_cast<Expr*>(BW);
431 Expr *Init = static_cast<Expr*>(InitExpr);
432 SourceLocation Loc = D.getIdentifierLoc();
433
Sebastian Redl669d5d72008-11-14 23:42:31 +0000434 bool isFunc = D.isFunctionDeclarator();
435
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000436 // C++ 9.2p6: A member shall not be declared to have automatic storage
437 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000438 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
439 // data members and cannot be applied to names declared const or static,
440 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000441 switch (DS.getStorageClassSpec()) {
442 case DeclSpec::SCS_unspecified:
443 case DeclSpec::SCS_typedef:
444 case DeclSpec::SCS_static:
445 // FALL THROUGH.
446 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000447 case DeclSpec::SCS_mutable:
448 if (isFunc) {
449 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000450 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000451 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000452 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
453
Sebastian Redla11f42f2008-11-17 23:24:37 +0000454 // FIXME: It would be nicer if the keyword was ignored only for this
455 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000456 D.getMutableDeclSpec().ClearStorageClassSpecs();
457 } else {
458 QualType T = GetTypeForDeclarator(D, S);
459 diag::kind err = static_cast<diag::kind>(0);
460 if (T->isReferenceType())
461 err = diag::err_mutable_reference;
462 else if (T.isConstQualified())
463 err = diag::err_mutable_const;
464 if (err != 0) {
465 if (DS.getStorageClassSpecLoc().isValid())
466 Diag(DS.getStorageClassSpecLoc(), err);
467 else
468 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000469 // FIXME: It would be nicer if the keyword was ignored only for this
470 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000471 D.getMutableDeclSpec().ClearStorageClassSpecs();
472 }
473 }
474 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000475 default:
476 if (DS.getStorageClassSpecLoc().isValid())
477 Diag(DS.getStorageClassSpecLoc(),
478 diag::err_storageclass_invalid_for_member);
479 else
480 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
481 D.getMutableDeclSpec().ClearStorageClassSpecs();
482 }
483
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000484 if (!isFunc &&
485 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
486 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000487 // Check also for this case:
488 //
489 // typedef int f();
490 // f a;
491 //
492 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
493 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
494 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000495
Sebastian Redl669d5d72008-11-14 23:42:31 +0000496 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
497 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000498 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000499
500 Decl *Member;
501 bool InvalidDecl = false;
502
503 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000504 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
505 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000506 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000507 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000508
509 if (!Member) return LastInGroup;
510
Douglas Gregor10bd3682008-11-17 22:58:34 +0000511 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000512
513 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
514 // specific methods. Use a wrapper class that can be used with all C++ class
515 // member decls.
516 CXXClassMemberWrapper(Member).setAccess(AS);
517
Douglas Gregor64bffa92008-11-05 16:20:31 +0000518 // C++ [dcl.init.aggr]p1:
519 // An aggregate is an array or a class (clause 9) with [...] no
520 // private or protected non-static data members (clause 11).
Sebastian Redl64b45f72009-01-05 20:52:13 +0000521 // A POD must be an aggregate.
522 if (isInstField && (AS == AS_private || AS == AS_protected)) {
523 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
524 Record->setAggregate(false);
525 Record->setPOD(false);
526 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000527
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000528 if (DS.isVirtualSpecified()) {
529 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
530 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
531 InvalidDecl = true;
532 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000533 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000534 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
535 CurClass->setAggregate(false);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000536 CurClass->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000537 CurClass->setPolymorphic(true);
538 }
539 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000540
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000541 // FIXME: The above definition of virtual is not sufficient. A function is
542 // also virtual if it overrides an already virtual function. This is important
543 // to do here because it decides the validity of a pure specifier.
544
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000545 if (BitWidth) {
546 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
547 // constant-expression be a value equal to zero.
548 // FIXME: Check this.
549
550 if (D.isFunctionDeclarator()) {
551 // FIXME: Emit diagnostic about only constructors taking base initializers
552 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000553 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000554 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000555 InvalidDecl = true;
556
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000557 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000558 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000559 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000560 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000561 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000562 InvalidDecl = true;
563 }
564
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000565 } else if (isa<FunctionDecl>(Member)) {
566 // A function typedef ("typedef int f(); f a;").
567 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000568 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000569 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000570 InvalidDecl = true;
571
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000572 } else if (isa<TypedefDecl>(Member)) {
573 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000574 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000575 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000576 InvalidDecl = true;
577
578 } else {
579 assert(isa<CXXClassVarDecl>(Member) &&
580 "Didn't we cover all member kinds?");
581 // C++ 9.6p3: A bit-field shall not be a static member.
582 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000583 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000584 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000585 InvalidDecl = true;
586 }
587 }
588
589 if (Init) {
590 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
591 // if it declares a static member of const integral or const enumeration
592 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000593 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
594 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000596 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000597 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
598 CVD->getType()->isIntegralType()) {
599 // constant-initializer
600 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000601 InvalidDecl = true;
602
603 } else {
604 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000605 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000606 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000607 InvalidDecl = true;
608 }
609
610 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000611 // not static member. perhaps virtual function?
612 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redlc9b580a2009-01-09 22:29:03 +0000613 // With declarators parsed the way they are, the parser cannot
614 // distinguish between a normal initializer and a pure-specifier.
615 // Thus this grotesque test.
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000616 IntegerLiteral *IL;
617 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
618 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
619 if (MD->isVirtual())
620 MD->setPure();
621 else {
622 Diag(Loc, diag::err_non_virtual_pure)
623 << Name << Init->getSourceRange();
624 InvalidDecl = true;
625 }
626 } else {
627 Diag(Loc, diag::err_member_function_initialization)
628 << Name << Init->getSourceRange();
629 InvalidDecl = true;
630 }
631 } else {
632 Diag(Loc, diag::err_member_initialization)
633 << Name << Init->getSourceRange();
634 InvalidDecl = true;
635 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000636 }
637 }
638
639 if (InvalidDecl)
640 Member->setInvalidDecl();
641
642 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000643 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000644 return LastInGroup;
645 }
646 return Member;
647}
648
Douglas Gregor7ad83902008-11-05 04:29:56 +0000649/// ActOnMemInitializer - Handle a C++ member initializer.
650Sema::MemInitResult
651Sema::ActOnMemInitializer(DeclTy *ConstructorD,
652 Scope *S,
653 IdentifierInfo *MemberOrBase,
654 SourceLocation IdLoc,
655 SourceLocation LParenLoc,
656 ExprTy **Args, unsigned NumArgs,
657 SourceLocation *CommaLocs,
658 SourceLocation RParenLoc) {
659 CXXConstructorDecl *Constructor
660 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
661 if (!Constructor) {
662 // The user wrote a constructor initializer on a function that is
663 // not a C++ constructor. Ignore the error for now, because we may
664 // have more member initializers coming; we'll diagnose it just
665 // once in ActOnMemInitializers.
666 return true;
667 }
668
669 CXXRecordDecl *ClassDecl = Constructor->getParent();
670
671 // C++ [class.base.init]p2:
672 // Names in a mem-initializer-id are looked up in the scope of the
673 // constructor’s class and, if not found in that scope, are looked
674 // up in the scope containing the constructor’s
675 // definition. [Note: if the constructor’s class contains a member
676 // with the same name as a direct or virtual base class of the
677 // class, a mem-initializer-id naming the member or base class and
678 // composed of a single identifier refers to the class member. A
679 // mem-initializer-id for the hidden base class may be specified
680 // using a qualified name. ]
681 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000682 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000683 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000684 if (Result.first != Result.second)
685 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000686
687 // FIXME: Handle members of an anonymous union.
688
689 if (Member) {
690 // FIXME: Perform direct initialization of the member.
691 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
692 }
693
694 // It didn't name a member, so see if it names a class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000695 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000696 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000697 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
698 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000699
700 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
701 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000702 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000703 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000704
705 // C++ [class.base.init]p2:
706 // [...] Unless the mem-initializer-id names a nonstatic data
707 // member of the constructor’s class or a direct or virtual base
708 // of that class, the mem-initializer is ill-formed. A
709 // mem-initializer-list can initialize a base class using any
710 // name that denotes that base class type.
711
712 // First, check for a direct base class.
713 const CXXBaseSpecifier *DirectBaseSpec = 0;
714 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
715 Base != ClassDecl->bases_end(); ++Base) {
716 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
717 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
718 // We found a direct base of this type. That's what we're
719 // initializing.
720 DirectBaseSpec = &*Base;
721 break;
722 }
723 }
724
725 // Check for a virtual base class.
726 // FIXME: We might be able to short-circuit this if we know in
727 // advance that there are no virtual bases.
728 const CXXBaseSpecifier *VirtualBaseSpec = 0;
729 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
730 // We haven't found a base yet; search the class hierarchy for a
731 // virtual base class.
732 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
733 /*DetectVirtual=*/false);
734 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
735 for (BasePaths::paths_iterator Path = Paths.begin();
736 Path != Paths.end(); ++Path) {
737 if (Path->back().Base->isVirtual()) {
738 VirtualBaseSpec = Path->back().Base;
739 break;
740 }
741 }
742 }
743 }
744
745 // C++ [base.class.init]p2:
746 // If a mem-initializer-id is ambiguous because it designates both
747 // a direct non-virtual base class and an inherited virtual base
748 // class, the mem-initializer is ill-formed.
749 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000750 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
751 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000752
753 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
754}
755
756
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000757void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
758 DeclTy *TagDecl,
759 SourceLocation LBrac,
760 SourceLocation RBrac) {
761 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.
1152 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1153 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001154 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001155 << TypedefD->getDeclName();
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
1379 Decl *PrevDecl =
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001380 LookupDecl(II, Decl::IDNS_Ordinary, DeclRegionScope, 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00001381 /*enableLazyBuiltinCreation=*/false,
1382 /*LookupInParent=*/false);
1383
1384 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1385 // This is an extended namespace definition.
1386 // Attach this namespace decl to the chain of extended namespace
1387 // definitions.
1388 OrigNS->setNextNamespace(Namespc);
1389 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001390
Douglas Gregor44b43212008-12-11 16:49:14 +00001391 // Remove the previous declaration from the scope.
1392 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001393 IdResolver.RemoveDecl(OrigNS);
1394 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001395 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001396 } else if (PrevDecl) {
1397 // This is an invalid name redefinition.
1398 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1399 << Namespc->getDeclName();
1400 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1401 Namespc->setInvalidDecl();
1402 // Continue on to push Namespc as current DeclContext and return it.
1403 }
1404
1405 PushOnScopeChains(Namespc, DeclRegionScope);
1406 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001407 // FIXME: Handle anonymous namespaces
1408 }
1409
1410 // Although we could have an invalid decl (i.e. the namespace name is a
1411 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001412 // FIXME: We should be able to push Namespc here, so that the
1413 // each DeclContext for the namespace has the declarations
1414 // that showed up in that particular namespace definition.
1415 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001416 return Namespc;
1417}
1418
1419/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1420/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1421void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1422 Decl *Dcl = static_cast<Decl *>(D);
1423 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1424 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1425 Namespc->setRBracLoc(RBrace);
1426 PopDeclContext();
1427}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001428
Douglas Gregorf780abc2008-12-30 03:27:21 +00001429Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1430 SourceLocation UsingLoc,
1431 SourceLocation NamespcLoc,
1432 const CXXScopeSpec &SS,
1433 SourceLocation IdentLoc,
1434 IdentifierInfo *NamespcName,
1435 AttributeList *AttrList) {
1436 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1437 assert(NamespcName && "Invalid NamespcName.");
1438 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1439
1440 // FIXME: This still requires lot more checks, and AST support.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001441
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001442 // Lookup namespace name.
1443 LookupCriteria Criteria(LookupCriteria::Namespace, /*RedeclarationOnly=*/false,
1444 /*CPlusPlus=*/true);
1445 Decl *NS = 0;
1446 if (SS.isSet())
1447 NS = LookupQualifiedName(static_cast<DeclContext*>(SS.getScopeRep()),
1448 NamespcName, Criteria);
1449 else
1450 NS = LookupName(S, NamespcName, Criteria);
1451
1452 if (NS) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001453 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1454 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001455 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001456 }
1457
1458 // FIXME: We ignore AttrList for now, and delete it to avoid leak.
1459 delete AttrList;
1460 return 0;
1461}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001462
1463/// AddCXXDirectInitializerToDecl - This action is called immediately after
1464/// ActOnDeclarator, when a C++ direct initializer is present.
1465/// e.g: "int x(1);"
1466void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1467 ExprTy **ExprTys, unsigned NumExprs,
1468 SourceLocation *CommaLocs,
1469 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001470 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001471 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001472
1473 // If there is no declaration, there was an error parsing it. Just ignore
1474 // the initializer.
1475 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001476 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001477 delete static_cast<Expr *>(ExprTys[i]);
1478 return;
1479 }
1480
1481 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1482 if (!VDecl) {
1483 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1484 RealDecl->setInvalidDecl();
1485 return;
1486 }
1487
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001488 // We will treat direct-initialization as a copy-initialization:
1489 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001490 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1491 //
1492 // Clients that want to distinguish between the two forms, can check for
1493 // direct initializer using VarDecl::hasCXXDirectInitializer().
1494 // A major benefit is that clients that don't particularly care about which
1495 // exactly form was it (like the CodeGen) can handle both cases without
1496 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001497
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001498 // C++ 8.5p11:
1499 // The form of initialization (using parentheses or '=') is generally
1500 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001501 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001502 QualType DeclInitType = VDecl->getType();
1503 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1504 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001505
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001506 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001507 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001508 = PerformInitializationByConstructor(DeclInitType,
1509 (Expr **)ExprTys, NumExprs,
1510 VDecl->getLocation(),
1511 SourceRange(VDecl->getLocation(),
1512 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001513 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001514 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001515 if (!Constructor) {
1516 RealDecl->setInvalidDecl();
1517 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001518
1519 // Let clients know that initialization was done with a direct
1520 // initializer.
1521 VDecl->setCXXDirectInitializer(true);
1522
1523 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1524 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001525 return;
1526 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001527
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001528 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001529 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1530 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001531 RealDecl->setInvalidDecl();
1532 return;
1533 }
1534
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001535 // Let clients know that initialization was done with a direct initializer.
1536 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001537
1538 assert(NumExprs == 1 && "Expected 1 expression");
1539 // Set the init expression, handles conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001540 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001541}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001542
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001543/// PerformInitializationByConstructor - Perform initialization by
1544/// constructor (C++ [dcl.init]p14), which may occur as part of
1545/// direct-initialization or copy-initialization. We are initializing
1546/// an object of type @p ClassType with the given arguments @p
1547/// Args. @p Loc is the location in the source code where the
1548/// initializer occurs (e.g., a declaration, member initializer,
1549/// functional cast, etc.) while @p Range covers the whole
1550/// initialization. @p InitEntity is the entity being initialized,
1551/// which may by the name of a declaration or a type. @p Kind is the
1552/// kind of initialization we're performing, which affects whether
1553/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001554/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001555/// when the initialization fails, emits a diagnostic and returns
1556/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001557CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001558Sema::PerformInitializationByConstructor(QualType ClassType,
1559 Expr **Args, unsigned NumArgs,
1560 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001561 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001562 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001563 const RecordType *ClassRec = ClassType->getAsRecordType();
1564 assert(ClassRec && "Can only initialize a class type here");
1565
1566 // C++ [dcl.init]p14:
1567 //
1568 // If the initialization is direct-initialization, or if it is
1569 // copy-initialization where the cv-unqualified version of the
1570 // source type is the same class as, or a derived class of, the
1571 // class of the destination, constructors are considered. The
1572 // applicable constructors are enumerated (13.3.1.3), and the
1573 // best one is chosen through overload resolution (13.3). The
1574 // constructor so selected is called to initialize the object,
1575 // with the initializer expression(s) as its argument(s). If no
1576 // constructor applies, or the overload resolution is ambiguous,
1577 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001578 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1579 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001580
1581 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001582 DeclarationName ConstructorName
1583 = Context.DeclarationNames.getCXXConstructorName(
1584 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001585 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001586 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001587 Con != ConEnd; ++Con) {
1588 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001589 if ((Kind == IK_Direct) ||
1590 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1591 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1592 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1593 }
1594
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001595 // FIXME: When we decide not to synthesize the implicitly-declared
1596 // constructors, we'll need to make them appear here.
1597
Douglas Gregor18fe5682008-11-03 20:45:27 +00001598 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001599 switch (BestViableFunction(CandidateSet, Best)) {
1600 case OR_Success:
1601 // We found a constructor. Return it.
1602 return cast<CXXConstructorDecl>(Best->Function);
1603
1604 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001605 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1606 << InitEntity << (unsigned)CandidateSet.size() << Range;
1607 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001608 return 0;
1609
1610 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001611 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001612 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1613 return 0;
1614 }
1615
1616 return 0;
1617}
1618
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001619/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1620/// determine whether they are reference-related,
1621/// reference-compatible, reference-compatible with added
1622/// qualification, or incompatible, for use in C++ initialization by
1623/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1624/// type, and the first type (T1) is the pointee type of the reference
1625/// type being initialized.
1626Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001627Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1628 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001629 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1630 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1631
1632 T1 = Context.getCanonicalType(T1);
1633 T2 = Context.getCanonicalType(T2);
1634 QualType UnqualT1 = T1.getUnqualifiedType();
1635 QualType UnqualT2 = T2.getUnqualifiedType();
1636
1637 // C++ [dcl.init.ref]p4:
1638 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1639 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1640 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001641 if (UnqualT1 == UnqualT2)
1642 DerivedToBase = false;
1643 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1644 DerivedToBase = true;
1645 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001646 return Ref_Incompatible;
1647
1648 // At this point, we know that T1 and T2 are reference-related (at
1649 // least).
1650
1651 // C++ [dcl.init.ref]p4:
1652 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1653 // reference-related to T2 and cv1 is the same cv-qualification
1654 // as, or greater cv-qualification than, cv2. For purposes of
1655 // overload resolution, cases for which cv1 is greater
1656 // cv-qualification than cv2 are identified as
1657 // reference-compatible with added qualification (see 13.3.3.2).
1658 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1659 return Ref_Compatible;
1660 else if (T1.isMoreQualifiedThan(T2))
1661 return Ref_Compatible_With_Added_Qualification;
1662 else
1663 return Ref_Related;
1664}
1665
1666/// CheckReferenceInit - Check the initialization of a reference
1667/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1668/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001669/// list), and DeclType is the type of the declaration. When ICS is
1670/// non-null, this routine will compute the implicit conversion
1671/// sequence according to C++ [over.ics.ref] and will not produce any
1672/// diagnostics; when ICS is null, it will emit diagnostics when any
1673/// errors are found. Either way, a return value of true indicates
1674/// that there was a failure, a return value of false indicates that
1675/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001676///
1677/// When @p SuppressUserConversions, user-defined conversions are
1678/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001679/// When @p AllowExplicit, we also permit explicit user-defined
1680/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001681bool
1682Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001683 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001684 bool SuppressUserConversions,
1685 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001686 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1687
1688 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1689 QualType T2 = Init->getType();
1690
Douglas Gregor904eed32008-11-10 20:40:00 +00001691 // If the initializer is the address of an overloaded function, try
1692 // to resolve the overloaded function. If all goes well, T2 is the
1693 // type of the resulting function.
1694 if (T2->isOverloadType()) {
1695 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1696 ICS != 0);
1697 if (Fn) {
1698 // Since we're performing this reference-initialization for
1699 // real, update the initializer with the resulting function.
1700 if (!ICS)
1701 FixOverloadedFunctionReference(Init, Fn);
1702
1703 T2 = Fn->getType();
1704 }
1705 }
1706
Douglas Gregor15da57e2008-10-29 02:00:59 +00001707 // Compute some basic properties of the types and the initializer.
1708 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001709 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001710 ReferenceCompareResult RefRelationship
1711 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1712
1713 // Most paths end in a failed conversion.
1714 if (ICS)
1715 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001716
1717 // C++ [dcl.init.ref]p5:
1718 // A reference to type “cv1 T1” is initialized by an expression
1719 // of type “cv2 T2” as follows:
1720
1721 // -- If the initializer expression
1722
1723 bool BindsDirectly = false;
1724 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1725 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001726 //
1727 // Note that the bit-field check is skipped if we are just computing
1728 // the implicit conversion sequence (C++ [over.best.ics]p2).
1729 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1730 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001731 BindsDirectly = true;
1732
Douglas Gregor15da57e2008-10-29 02:00:59 +00001733 if (ICS) {
1734 // C++ [over.ics.ref]p1:
1735 // When a parameter of reference type binds directly (8.5.3)
1736 // to an argument expression, the implicit conversion sequence
1737 // is the identity conversion, unless the argument expression
1738 // has a type that is a derived class of the parameter type,
1739 // in which case the implicit conversion sequence is a
1740 // derived-to-base Conversion (13.3.3.1).
1741 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1742 ICS->Standard.First = ICK_Identity;
1743 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1744 ICS->Standard.Third = ICK_Identity;
1745 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1746 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001747 ICS->Standard.ReferenceBinding = true;
1748 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001749
1750 // Nothing more to do: the inaccessibility/ambiguity check for
1751 // derived-to-base conversions is suppressed when we're
1752 // computing the implicit conversion sequence (C++
1753 // [over.best.ics]p2).
1754 return false;
1755 } else {
1756 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001757 // FIXME: Binding to a subobject of the lvalue is going to require
1758 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001759 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001760 }
1761 }
1762
1763 // -- has a class type (i.e., T2 is a class type) and can be
1764 // implicitly converted to an lvalue of type “cv3 T3,”
1765 // where “cv1 T1” is reference-compatible with “cv3 T3”
1766 // 92) (this conversion is selected by enumerating the
1767 // applicable conversion functions (13.3.1.6) and choosing
1768 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001769 if (!SuppressUserConversions && T2->isRecordType()) {
1770 // FIXME: Look for conversions in base classes!
1771 CXXRecordDecl *T2RecordDecl
1772 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001773
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001774 OverloadCandidateSet CandidateSet;
1775 OverloadedFunctionDecl *Conversions
1776 = T2RecordDecl->getConversionFunctions();
1777 for (OverloadedFunctionDecl::function_iterator Func
1778 = Conversions->function_begin();
1779 Func != Conversions->function_end(); ++Func) {
1780 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1781
1782 // If the conversion function doesn't return a reference type,
1783 // it can't be considered for this conversion.
1784 // FIXME: This will change when we support rvalue references.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001785 if (Conv->getConversionType()->isReferenceType() &&
1786 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001787 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1788 }
1789
1790 OverloadCandidateSet::iterator Best;
1791 switch (BestViableFunction(CandidateSet, Best)) {
1792 case OR_Success:
1793 // This is a direct binding.
1794 BindsDirectly = true;
1795
1796 if (ICS) {
1797 // C++ [over.ics.ref]p1:
1798 //
1799 // [...] If the parameter binds directly to the result of
1800 // applying a conversion function to the argument
1801 // expression, the implicit conversion sequence is a
1802 // user-defined conversion sequence (13.3.3.1.2), with the
1803 // second standard conversion sequence either an identity
1804 // conversion or, if the conversion function returns an
1805 // entity of a type that is a derived class of the parameter
1806 // type, a derived-to-base Conversion.
1807 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1808 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1809 ICS->UserDefined.After = Best->FinalConversion;
1810 ICS->UserDefined.ConversionFunction = Best->Function;
1811 assert(ICS->UserDefined.After.ReferenceBinding &&
1812 ICS->UserDefined.After.DirectBinding &&
1813 "Expected a direct reference binding!");
1814 return false;
1815 } else {
1816 // Perform the conversion.
1817 // FIXME: Binding to a subobject of the lvalue is going to require
1818 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001819 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001820 }
1821 break;
1822
1823 case OR_Ambiguous:
1824 assert(false && "Ambiguous reference binding conversions not implemented.");
1825 return true;
1826
1827 case OR_No_Viable_Function:
1828 // There was no suitable conversion; continue with other checks.
1829 break;
1830 }
1831 }
1832
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001833 if (BindsDirectly) {
1834 // C++ [dcl.init.ref]p4:
1835 // [...] In all cases where the reference-related or
1836 // reference-compatible relationship of two types is used to
1837 // establish the validity of a reference binding, and T1 is a
1838 // base class of T2, a program that necessitates such a binding
1839 // is ill-formed if T1 is an inaccessible (clause 11) or
1840 // ambiguous (10.2) base class of T2.
1841 //
1842 // Note that we only check this condition when we're allowed to
1843 // complain about errors, because we should not be checking for
1844 // ambiguity (or inaccessibility) unless the reference binding
1845 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001846 if (DerivedToBase)
1847 return CheckDerivedToBaseConversion(T2, T1,
1848 Init->getSourceRange().getBegin(),
1849 Init->getSourceRange());
1850 else
1851 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001852 }
1853
1854 // -- Otherwise, the reference shall be to a non-volatile const
1855 // type (i.e., cv1 shall be const).
1856 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001857 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001858 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001859 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001860 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1861 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001862 return true;
1863 }
1864
1865 // -- If the initializer expression is an rvalue, with T2 a
1866 // class type, and “cv1 T1” is reference-compatible with
1867 // “cv2 T2,” the reference is bound in one of the
1868 // following ways (the choice is implementation-defined):
1869 //
1870 // -- The reference is bound to the object represented by
1871 // the rvalue (see 3.10) or to a sub-object within that
1872 // object.
1873 //
1874 // -- A temporary of type “cv1 T2” [sic] is created, and
1875 // a constructor is called to copy the entire rvalue
1876 // object into the temporary. The reference is bound to
1877 // the temporary or to a sub-object within the
1878 // temporary.
1879 //
1880 //
1881 // The constructor that would be used to make the copy
1882 // shall be callable whether or not the copy is actually
1883 // done.
1884 //
1885 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1886 // freedom, so we will always take the first option and never build
1887 // a temporary in this case. FIXME: We will, however, have to check
1888 // for the presence of a copy constructor in C++98/03 mode.
1889 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001890 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1891 if (ICS) {
1892 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1893 ICS->Standard.First = ICK_Identity;
1894 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1895 ICS->Standard.Third = ICK_Identity;
1896 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1897 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001898 ICS->Standard.ReferenceBinding = true;
1899 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001900 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001901 // FIXME: Binding to a subobject of the rvalue is going to require
1902 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001903 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001904 }
1905 return false;
1906 }
1907
1908 // -- Otherwise, a temporary of type “cv1 T1” is created and
1909 // initialized from the initializer expression using the
1910 // rules for a non-reference copy initialization (8.5). The
1911 // reference is then bound to the temporary. If T1 is
1912 // reference-related to T2, cv1 must be the same
1913 // cv-qualification as, or greater cv-qualification than,
1914 // cv2; otherwise, the program is ill-formed.
1915 if (RefRelationship == Ref_Related) {
1916 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1917 // we would be reference-compatible or reference-compatible with
1918 // added qualification. But that wasn't the case, so the reference
1919 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001920 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001921 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001922 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001923 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1924 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001925 return true;
1926 }
1927
1928 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001929 if (ICS) {
1930 /// C++ [over.ics.ref]p2:
1931 ///
1932 /// When a parameter of reference type is not bound directly to
1933 /// an argument expression, the conversion sequence is the one
1934 /// required to convert the argument expression to the
1935 /// underlying type of the reference according to
1936 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1937 /// to copy-initializing a temporary of the underlying type with
1938 /// the argument expression. Any difference in top-level
1939 /// cv-qualification is subsumed by the initialization itself
1940 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001941 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001942 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1943 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00001944 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00001945 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001946}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001947
1948/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1949/// of this overloaded operator is well-formed. If so, returns false;
1950/// otherwise, emits appropriate diagnostics and returns true.
1951bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001952 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001953 "Expected an overloaded operator declaration");
1954
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001955 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1956
1957 // C++ [over.oper]p5:
1958 // The allocation and deallocation functions, operator new,
1959 // operator new[], operator delete and operator delete[], are
1960 // described completely in 3.7.3. The attributes and restrictions
1961 // found in the rest of this subclause do not apply to them unless
1962 // explicitly stated in 3.7.3.
1963 // FIXME: Write a separate routine for checking this. For now, just
1964 // allow it.
1965 if (Op == OO_New || Op == OO_Array_New ||
1966 Op == OO_Delete || Op == OO_Array_Delete)
1967 return false;
1968
1969 // C++ [over.oper]p6:
1970 // An operator function shall either be a non-static member
1971 // function or be a non-member function and have at least one
1972 // parameter whose type is a class, a reference to a class, an
1973 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001974 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1975 if (MethodDecl->isStatic())
1976 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001977 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001978 } else {
1979 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001980 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1981 ParamEnd = FnDecl->param_end();
1982 Param != ParamEnd; ++Param) {
1983 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001984 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1985 ClassOrEnumParam = true;
1986 break;
1987 }
1988 }
1989
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001990 if (!ClassOrEnumParam)
1991 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001992 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001993 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001994 }
1995
1996 // C++ [over.oper]p8:
1997 // An operator function cannot have default arguments (8.3.6),
1998 // except where explicitly stated below.
1999 //
2000 // Only the function-call operator allows default arguments
2001 // (C++ [over.call]p1).
2002 if (Op != OO_Call) {
2003 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2004 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002005 if ((*Param)->hasUnparsedDefaultArg())
2006 return Diag((*Param)->getLocation(),
2007 diag::err_operator_overload_default_arg)
2008 << FnDecl->getDeclName();
2009 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002010 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002011 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002012 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002013 }
2014 }
2015
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002016 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2017 { false, false, false }
2018#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2019 , { Unary, Binary, MemberOnly }
2020#include "clang/Basic/OperatorKinds.def"
2021 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002022
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002023 bool CanBeUnaryOperator = OperatorUses[Op][0];
2024 bool CanBeBinaryOperator = OperatorUses[Op][1];
2025 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002026
2027 // C++ [over.oper]p8:
2028 // [...] Operator functions cannot have more or fewer parameters
2029 // than the number required for the corresponding operator, as
2030 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002031 unsigned NumParams = FnDecl->getNumParams()
2032 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002033 if (Op != OO_Call &&
2034 ((NumParams == 1 && !CanBeUnaryOperator) ||
2035 (NumParams == 2 && !CanBeBinaryOperator) ||
2036 (NumParams < 1) || (NumParams > 2))) {
2037 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002038 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002039 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002040 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002041 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002042 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002043 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002044 assert(CanBeBinaryOperator &&
2045 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002046 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002047 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002048
Chris Lattner416e46f2008-11-21 07:57:12 +00002049 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002050 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002051 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002052
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002053 // Overloaded operators other than operator() cannot be variadic.
2054 if (Op != OO_Call &&
2055 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002056 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002057 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002058 }
2059
2060 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002061 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2062 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002063 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002064 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002065 }
2066
2067 // C++ [over.inc]p1:
2068 // The user-defined function called operator++ implements the
2069 // prefix and postfix ++ operator. If this function is a member
2070 // function with no parameters, or a non-member function with one
2071 // parameter of class or enumeration type, it defines the prefix
2072 // increment operator ++ for objects of that type. If the function
2073 // is a member function with one parameter (which shall be of type
2074 // int) or a non-member function with two parameters (the second
2075 // of which shall be of type int), it defines the postfix
2076 // increment operator ++ for objects of that type.
2077 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2078 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2079 bool ParamIsInt = false;
2080 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2081 ParamIsInt = BT->getKind() == BuiltinType::Int;
2082
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002083 if (!ParamIsInt)
2084 return Diag(LastParam->getLocation(),
2085 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002086 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002087 }
2088
Sebastian Redl64b45f72009-01-05 20:52:13 +00002089 // Notify the class if it got an assignment operator.
2090 if (Op == OO_Equal) {
2091 // Would have returned earlier otherwise.
2092 assert(isa<CXXMethodDecl>(FnDecl) &&
2093 "Overloaded = not member, but not filtered.");
2094 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2095 Method->getParent()->addedAssignmentOperator(Context, Method);
2096 }
2097
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002098 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002099}
Chris Lattner5a003a42008-12-17 07:09:26 +00002100
Douglas Gregor074149e2009-01-05 19:45:36 +00002101/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2102/// linkage specification, including the language and (if present)
2103/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2104/// the location of the language string literal, which is provided
2105/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2106/// the '{' brace. Otherwise, this linkage specification does not
2107/// have any braces.
2108Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2109 SourceLocation ExternLoc,
2110 SourceLocation LangLoc,
2111 const char *Lang,
2112 unsigned StrSize,
2113 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002114 LinkageSpecDecl::LanguageIDs Language;
2115 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2116 Language = LinkageSpecDecl::lang_c;
2117 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2118 Language = LinkageSpecDecl::lang_cxx;
2119 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002120 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002121 return 0;
2122 }
2123
2124 // FIXME: Add all the various semantics of linkage specifications
2125
Douglas Gregor074149e2009-01-05 19:45:36 +00002126 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2127 LangLoc, Language,
2128 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002129 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002130 PushDeclContext(S, D);
2131 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002132}
2133
Douglas Gregor074149e2009-01-05 19:45:36 +00002134/// ActOnFinishLinkageSpecification - Completely the definition of
2135/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2136/// valid, it's the position of the closing '}' brace in a linkage
2137/// specification that uses braces.
2138Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2139 DeclTy *LinkageSpec,
2140 SourceLocation RBraceLoc) {
2141 if (LinkageSpec)
2142 PopDeclContext();
2143 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002144}
2145
Sebastian Redl4b07b292008-12-22 19:15:10 +00002146/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2147/// handler.
2148Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2149{
2150 QualType ExDeclType = GetTypeForDeclarator(D, S);
2151 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2152
2153 bool Invalid = false;
2154
2155 // Arrays and functions decay.
2156 if (ExDeclType->isArrayType())
2157 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2158 else if (ExDeclType->isFunctionType())
2159 ExDeclType = Context.getPointerType(ExDeclType);
2160
2161 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2162 // The exception-declaration shall not denote a pointer or reference to an
2163 // incomplete type, other than [cv] void*.
2164 QualType BaseType = ExDeclType;
2165 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002166 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002167 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2168 BaseType = Ptr->getPointeeType();
2169 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002170 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002171 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2172 BaseType = Ref->getPointeeType();
2173 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002174 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002175 }
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002176 if ((Mode == 0 || !BaseType->isVoidType()) &&
2177 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00002178 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002179
Sebastian Redl8351da02008-12-22 21:35:02 +00002180 // FIXME: Need to test for ability to copy-construct and destroy the
2181 // exception variable.
2182 // FIXME: Need to check for abstract classes.
2183
Sebastian Redl4b07b292008-12-22 19:15:10 +00002184 IdentifierInfo *II = D.getIdentifier();
2185 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2186 // The scope should be freshly made just for us. There is just no way
2187 // it contains any previous declaration.
2188 assert(!S->isDeclScope(PrevDecl));
2189 if (PrevDecl->isTemplateParameter()) {
2190 // Maybe we will complain about the shadowed template parameter.
2191 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2192
2193 }
2194 }
2195
2196 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002197 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002198 if (D.getInvalidType() || Invalid)
2199 ExDecl->setInvalidDecl();
2200
2201 if (D.getCXXScopeSpec().isSet()) {
2202 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2203 << D.getCXXScopeSpec().getRange();
2204 ExDecl->setInvalidDecl();
2205 }
2206
2207 // Add the exception declaration into this scope.
2208 S->AddDecl(ExDecl);
2209 if (II)
2210 IdResolver.AddDecl(ExDecl);
2211
2212 ProcessDeclAttributes(ExDecl, D);
2213 return ExDecl;
2214}