blob: 33a31c7500df83a0f959b98490e79ea9f8966915 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
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.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000342 if (BaseType->isIncompleteType())
343 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000344
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000345 // If the base class is polymorphic, the new one is, too.
346 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
347 assert(BaseDecl && "Record type has no declaration");
348 BaseDecl = BaseDecl->getDefinition(Context);
349 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000350 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl64b45f72009-01-05 20:52:13 +0000351 Decl->setPolymorphic(true);
352
353 // C++ [dcl.init.aggr]p1:
354 // An aggregate is [...] a class with [...] no base classes [...].
355 Decl->setAggregate(false);
356 Decl->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000357
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000358 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000359 return new CXXBaseSpecifier(SpecifierRange, Virtual,
360 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000361}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000362
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000363/// ActOnBaseSpecifiers - Attach the given base specifiers to the
364/// class, after checking whether there are any duplicate base
365/// classes.
366void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
367 unsigned NumBases) {
368 if (NumBases == 0)
369 return;
370
371 // Used to keep track of which base types we have already seen, so
372 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000373 // that the key is always the unqualified canonical type of the base
374 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000375 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
376
377 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000378 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
379 unsigned NumGoodBases = 0;
380 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000381 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000382 = Context.getCanonicalType(BaseSpecs[idx]->getType());
383 NewBaseType = NewBaseType.getUnqualifiedType();
384
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000385 if (KnownBaseTypes[NewBaseType]) {
386 // C++ [class.mi]p3:
387 // A class shall not be specified as a direct base class of a
388 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000389 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000390 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000391 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000392 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000393
394 // Delete the duplicate base class specifier; we're going to
395 // overwrite its pointer later.
396 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000397 } else {
398 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000399 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
400 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000401 }
402 }
403
404 // Attach the remaining base class specifiers to the derived class.
405 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000406 Decl->setBases(BaseSpecs, NumGoodBases);
407
408 // Delete the remaining (good) base class specifiers, since their
409 // data has been copied into the CXXRecordDecl.
410 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
411 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000412}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000413
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000414//===----------------------------------------------------------------------===//
415// C++ class member Handling
416//===----------------------------------------------------------------------===//
417
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000418/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
419/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
420/// bitfield width if there is one and 'InitExpr' specifies the initializer if
421/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
422/// declarators on it.
423///
Douglas Gregor72b505b2008-12-16 21:30:33 +0000424/// FIXME: The note below is out-of-date.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000425/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
426/// an instance field is declared, a new CXXFieldDecl is created but the method
427/// does *not* return it; it returns LastInGroup instead. The other C++ members
428/// (which are all ScopedDecls) are returned after appending them to
429/// LastInGroup.
430Sema::DeclTy *
431Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
432 ExprTy *BW, ExprTy *InitExpr,
433 DeclTy *LastInGroup) {
434 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000435 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000436 Expr *BitWidth = static_cast<Expr*>(BW);
437 Expr *Init = static_cast<Expr*>(InitExpr);
438 SourceLocation Loc = D.getIdentifierLoc();
439
Sebastian Redl669d5d72008-11-14 23:42:31 +0000440 bool isFunc = D.isFunctionDeclarator();
441
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000442 // C++ 9.2p6: A member shall not be declared to have automatic storage
443 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000444 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
445 // data members and cannot be applied to names declared const or static,
446 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000447 switch (DS.getStorageClassSpec()) {
448 case DeclSpec::SCS_unspecified:
449 case DeclSpec::SCS_typedef:
450 case DeclSpec::SCS_static:
451 // FALL THROUGH.
452 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000453 case DeclSpec::SCS_mutable:
454 if (isFunc) {
455 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000456 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000457 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000458 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
459
Sebastian Redla11f42f2008-11-17 23:24:37 +0000460 // FIXME: It would be nicer if the keyword was ignored only for this
461 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000462 D.getMutableDeclSpec().ClearStorageClassSpecs();
463 } else {
464 QualType T = GetTypeForDeclarator(D, S);
465 diag::kind err = static_cast<diag::kind>(0);
466 if (T->isReferenceType())
467 err = diag::err_mutable_reference;
468 else if (T.isConstQualified())
469 err = diag::err_mutable_const;
470 if (err != 0) {
471 if (DS.getStorageClassSpecLoc().isValid())
472 Diag(DS.getStorageClassSpecLoc(), err);
473 else
474 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000475 // FIXME: It would be nicer if the keyword was ignored only for this
476 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000477 D.getMutableDeclSpec().ClearStorageClassSpecs();
478 }
479 }
480 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000481 default:
482 if (DS.getStorageClassSpecLoc().isValid())
483 Diag(DS.getStorageClassSpecLoc(),
484 diag::err_storageclass_invalid_for_member);
485 else
486 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
487 D.getMutableDeclSpec().ClearStorageClassSpecs();
488 }
489
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000490 if (!isFunc &&
491 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
492 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000493 // Check also for this case:
494 //
495 // typedef int f();
496 // f a;
497 //
498 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
499 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
500 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000501
Sebastian Redl669d5d72008-11-14 23:42:31 +0000502 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
503 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000504 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000505
506 Decl *Member;
507 bool InvalidDecl = false;
508
509 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000510 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
511 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000512 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000513 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000514
515 if (!Member) return LastInGroup;
516
Douglas Gregor10bd3682008-11-17 22:58:34 +0000517 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000518
519 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
520 // specific methods. Use a wrapper class that can be used with all C++ class
521 // member decls.
522 CXXClassMemberWrapper(Member).setAccess(AS);
523
Douglas Gregor64bffa92008-11-05 16:20:31 +0000524 // C++ [dcl.init.aggr]p1:
525 // An aggregate is an array or a class (clause 9) with [...] no
526 // private or protected non-static data members (clause 11).
Sebastian Redl64b45f72009-01-05 20:52:13 +0000527 // A POD must be an aggregate.
528 if (isInstField && (AS == AS_private || AS == AS_protected)) {
529 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
530 Record->setAggregate(false);
531 Record->setPOD(false);
532 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000533
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000534 if (DS.isVirtualSpecified()) {
535 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
536 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
537 InvalidDecl = true;
538 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000539 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000540 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
541 CurClass->setAggregate(false);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000542 CurClass->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000543 CurClass->setPolymorphic(true);
544 }
545 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000546
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000547 // FIXME: The above definition of virtual is not sufficient. A function is
548 // also virtual if it overrides an already virtual function. This is important
549 // to do here because it decides the validity of a pure specifier.
550
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000551 if (BitWidth) {
552 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
553 // constant-expression be a value equal to zero.
554 // FIXME: Check this.
555
556 if (D.isFunctionDeclarator()) {
557 // FIXME: Emit diagnostic about only constructors taking base initializers
558 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000559 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000560 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000561 InvalidDecl = true;
562
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000563 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000564 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000565 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000566 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000567 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568 InvalidDecl = true;
569 }
570
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000571 } else if (isa<FunctionDecl>(Member)) {
572 // A function typedef ("typedef int f(); f a;").
573 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000574 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000575 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000576 InvalidDecl = true;
577
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000578 } else if (isa<TypedefDecl>(Member)) {
579 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000580 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000581 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000582 InvalidDecl = true;
583
584 } else {
585 assert(isa<CXXClassVarDecl>(Member) &&
586 "Didn't we cover all member kinds?");
587 // C++ 9.6p3: A bit-field shall not be a static member.
588 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000590 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000591 InvalidDecl = true;
592 }
593 }
594
595 if (Init) {
596 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
597 // if it declares a static member of const integral or const enumeration
598 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000599 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
600 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000601 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000602 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000603 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
604 CVD->getType()->isIntegralType()) {
605 // constant-initializer
606 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000607 InvalidDecl = true;
608
609 } else {
610 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000611 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000612 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000613 InvalidDecl = true;
614 }
615
616 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000617 // not static member. perhaps virtual function?
618 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redlc9b580a2009-01-09 22:29:03 +0000619 // With declarators parsed the way they are, the parser cannot
620 // distinguish between a normal initializer and a pure-specifier.
621 // Thus this grotesque test.
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000622 IntegerLiteral *IL;
623 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
624 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
625 if (MD->isVirtual())
626 MD->setPure();
627 else {
628 Diag(Loc, diag::err_non_virtual_pure)
629 << Name << Init->getSourceRange();
630 InvalidDecl = true;
631 }
632 } else {
633 Diag(Loc, diag::err_member_function_initialization)
634 << Name << Init->getSourceRange();
635 InvalidDecl = true;
636 }
637 } else {
638 Diag(Loc, diag::err_member_initialization)
639 << Name << Init->getSourceRange();
640 InvalidDecl = true;
641 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000642 }
643 }
644
645 if (InvalidDecl)
646 Member->setInvalidDecl();
647
648 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000649 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000650 return LastInGroup;
651 }
652 return Member;
653}
654
Douglas Gregor7ad83902008-11-05 04:29:56 +0000655/// ActOnMemInitializer - Handle a C++ member initializer.
656Sema::MemInitResult
657Sema::ActOnMemInitializer(DeclTy *ConstructorD,
658 Scope *S,
659 IdentifierInfo *MemberOrBase,
660 SourceLocation IdLoc,
661 SourceLocation LParenLoc,
662 ExprTy **Args, unsigned NumArgs,
663 SourceLocation *CommaLocs,
664 SourceLocation RParenLoc) {
665 CXXConstructorDecl *Constructor
666 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
667 if (!Constructor) {
668 // The user wrote a constructor initializer on a function that is
669 // not a C++ constructor. Ignore the error for now, because we may
670 // have more member initializers coming; we'll diagnose it just
671 // once in ActOnMemInitializers.
672 return true;
673 }
674
675 CXXRecordDecl *ClassDecl = Constructor->getParent();
676
677 // C++ [class.base.init]p2:
678 // Names in a mem-initializer-id are looked up in the scope of the
679 // constructor’s class and, if not found in that scope, are looked
680 // up in the scope containing the constructor’s
681 // definition. [Note: if the constructor’s class contains a member
682 // with the same name as a direct or virtual base class of the
683 // class, a mem-initializer-id naming the member or base class and
684 // composed of a single identifier refers to the class member. A
685 // mem-initializer-id for the hidden base class may be specified
686 // using a qualified name. ]
687 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000688 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000689 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000690 if (Result.first != Result.second)
691 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000692
693 // FIXME: Handle members of an anonymous union.
694
695 if (Member) {
696 // FIXME: Perform direct initialization of the member.
697 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
698 }
699
700 // It didn't name a member, so see if it names a class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000701 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000702 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000703 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
704 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000705
706 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
707 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000708 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000709 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000710
711 // C++ [class.base.init]p2:
712 // [...] Unless the mem-initializer-id names a nonstatic data
713 // member of the constructor’s class or a direct or virtual base
714 // of that class, the mem-initializer is ill-formed. A
715 // mem-initializer-list can initialize a base class using any
716 // name that denotes that base class type.
717
718 // First, check for a direct base class.
719 const CXXBaseSpecifier *DirectBaseSpec = 0;
720 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
721 Base != ClassDecl->bases_end(); ++Base) {
722 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
723 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
724 // We found a direct base of this type. That's what we're
725 // initializing.
726 DirectBaseSpec = &*Base;
727 break;
728 }
729 }
730
731 // Check for a virtual base class.
732 // FIXME: We might be able to short-circuit this if we know in
733 // advance that there are no virtual bases.
734 const CXXBaseSpecifier *VirtualBaseSpec = 0;
735 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
736 // We haven't found a base yet; search the class hierarchy for a
737 // virtual base class.
738 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
739 /*DetectVirtual=*/false);
740 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
741 for (BasePaths::paths_iterator Path = Paths.begin();
742 Path != Paths.end(); ++Path) {
743 if (Path->back().Base->isVirtual()) {
744 VirtualBaseSpec = Path->back().Base;
745 break;
746 }
747 }
748 }
749 }
750
751 // C++ [base.class.init]p2:
752 // If a mem-initializer-id is ambiguous because it designates both
753 // a direct non-virtual base class and an inherited virtual base
754 // class, the mem-initializer is ill-formed.
755 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000756 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
757 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000758
759 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
760}
761
762
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000763void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
764 DeclTy *TagDecl,
765 SourceLocation LBrac,
766 SourceLocation RBrac) {
767 ActOnFields(S, RLoc, TagDecl,
768 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000769 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor61366e92008-12-24 00:01:03 +0000770 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000771}
772
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000773/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
774/// special functions, such as the default constructor, copy
775/// constructor, or destructor, to the given C++ class (C++
776/// [special]p1). This routine can only be executed just before the
777/// definition of the class is complete.
778void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000779 QualType ClassType = Context.getTypeDeclType(ClassDecl);
780 ClassType = Context.getCanonicalType(ClassType);
781
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000782 if (!ClassDecl->hasUserDeclaredConstructor()) {
783 // C++ [class.ctor]p5:
784 // A default constructor for a class X is a constructor of class X
785 // that can be called without an argument. If there is no
786 // user-declared constructor for class X, a default constructor is
787 // implicitly declared. An implicitly-declared default constructor
788 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000789 DeclarationName Name
790 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000791 CXXConstructorDecl *DefaultCon =
792 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000793 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000794 Context.getFunctionType(Context.VoidTy,
795 0, 0, false, 0),
796 /*isExplicit=*/false,
797 /*isInline=*/true,
798 /*isImplicitlyDeclared=*/true);
799 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000800 DefaultCon->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000801 ClassDecl->addDecl(DefaultCon);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000802
803 // Notify the class that we've added a constructor.
804 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000805 }
806
807 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
808 // C++ [class.copy]p4:
809 // If the class definition does not explicitly declare a copy
810 // constructor, one is declared implicitly.
811
812 // C++ [class.copy]p5:
813 // The implicitly-declared copy constructor for a class X will
814 // have the form
815 //
816 // X::X(const X&)
817 //
818 // if
819 bool HasConstCopyConstructor = true;
820
821 // -- each direct or virtual base class B of X has a copy
822 // constructor whose first parameter is of type const B& or
823 // const volatile B&, and
824 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
825 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
826 const CXXRecordDecl *BaseClassDecl
827 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
828 HasConstCopyConstructor
829 = BaseClassDecl->hasConstCopyConstructor(Context);
830 }
831
832 // -- for all the nonstatic data members of X that are of a
833 // class type M (or array thereof), each such class type
834 // has a copy constructor whose first parameter is of type
835 // const M& or const volatile M&.
836 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
837 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
838 QualType FieldType = (*Field)->getType();
839 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
840 FieldType = Array->getElementType();
841 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
842 const CXXRecordDecl *FieldClassDecl
843 = cast<CXXRecordDecl>(FieldClassType->getDecl());
844 HasConstCopyConstructor
845 = FieldClassDecl->hasConstCopyConstructor(Context);
846 }
847 }
848
Sebastian Redl64b45f72009-01-05 20:52:13 +0000849 // Otherwise, the implicitly declared copy constructor will have
850 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000851 //
852 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +0000853 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000854 if (HasConstCopyConstructor)
855 ArgType = ArgType.withConst();
856 ArgType = Context.getReferenceType(ArgType);
857
Sebastian Redl64b45f72009-01-05 20:52:13 +0000858 // An implicitly-declared copy constructor is an inline public
859 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000860 DeclarationName Name
861 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000862 CXXConstructorDecl *CopyConstructor
863 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000864 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000865 Context.getFunctionType(Context.VoidTy,
866 &ArgType, 1,
867 false, 0),
868 /*isExplicit=*/false,
869 /*isInline=*/true,
870 /*isImplicitlyDeclared=*/true);
871 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000872 CopyConstructor->setImplicit();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000873
874 // Add the parameter to the constructor.
875 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
876 ClassDecl->getLocation(),
877 /*IdentifierInfo=*/0,
878 ArgType, VarDecl::None, 0, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000879 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000880
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000881 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor482b77d2009-01-12 23:27:07 +0000882 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000883 }
884
Sebastian Redl64b45f72009-01-05 20:52:13 +0000885 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
886 // Note: The following rules are largely analoguous to the copy
887 // constructor rules. Note that virtual bases are not taken into account
888 // for determining the argument type of the operator. Note also that
889 // operators taking an object instead of a reference are allowed.
890 //
891 // C++ [class.copy]p10:
892 // If the class definition does not explicitly declare a copy
893 // assignment operator, one is declared implicitly.
894 // The implicitly-defined copy assignment operator for a class X
895 // will have the form
896 //
897 // X& X::operator=(const X&)
898 //
899 // if
900 bool HasConstCopyAssignment = true;
901
902 // -- each direct base class B of X has a copy assignment operator
903 // whose parameter is of type const B&, const volatile B& or B,
904 // and
905 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
906 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
907 const CXXRecordDecl *BaseClassDecl
908 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
909 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
910 }
911
912 // -- for all the nonstatic data members of X that are of a class
913 // type M (or array thereof), each such class type has a copy
914 // assignment operator whose parameter is of type const M&,
915 // const volatile M& or M.
916 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
917 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
918 QualType FieldType = (*Field)->getType();
919 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
920 FieldType = Array->getElementType();
921 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
922 const CXXRecordDecl *FieldClassDecl
923 = cast<CXXRecordDecl>(FieldClassType->getDecl());
924 HasConstCopyAssignment
925 = FieldClassDecl->hasConstCopyAssignment(Context);
926 }
927 }
928
929 // Otherwise, the implicitly declared copy assignment operator will
930 // have the form
931 //
932 // X& X::operator=(X&)
933 QualType ArgType = ClassType;
934 QualType RetType = Context.getReferenceType(ArgType);
935 if (HasConstCopyAssignment)
936 ArgType = ArgType.withConst();
937 ArgType = Context.getReferenceType(ArgType);
938
939 // An implicitly-declared copy assignment operator is an inline public
940 // member of its class.
941 DeclarationName Name =
942 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
943 CXXMethodDecl *CopyAssignment =
944 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
945 Context.getFunctionType(RetType, &ArgType, 1,
946 false, 0),
947 /*isStatic=*/false, /*isInline=*/true, 0);
948 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000949 CopyAssignment->setImplicit();
Sebastian Redl64b45f72009-01-05 20:52:13 +0000950
951 // Add the parameter to the operator.
952 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
953 ClassDecl->getLocation(),
954 /*IdentifierInfo=*/0,
955 ArgType, VarDecl::None, 0, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000956 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000957
958 // Don't call addedAssignmentOperator. There is no way to distinguish an
959 // implicit from an explicit assignment operator.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000960 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000961 }
962
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000963 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000964 // C++ [class.dtor]p2:
965 // If a class has no user-declared destructor, a destructor is
966 // declared implicitly. An implicitly-declared destructor is an
967 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000968 DeclarationName Name
969 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000970 CXXDestructorDecl *Destructor
971 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000972 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000973 Context.getFunctionType(Context.VoidTy,
974 0, 0, false, 0),
975 /*isInline=*/true,
976 /*isImplicitlyDeclared=*/true);
977 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000978 Destructor->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000979 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000980 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000981}
982
Douglas Gregor72b505b2008-12-16 21:30:33 +0000983/// ActOnStartDelayedCXXMethodDeclaration - We have completed
984/// parsing a top-level (non-nested) C++ class, and we are now
985/// parsing those parts of the given Method declaration that could
986/// not be parsed earlier (C++ [class.mem]p2), such as default
987/// arguments. This action should enter the scope of the given
988/// Method declaration as if we had just parsed the qualified method
989/// name. However, it should not bring the parameters into scope;
990/// that will be performed by ActOnDelayedCXXMethodParameter.
991void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
992 CXXScopeSpec SS;
993 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
994 ActOnCXXEnterDeclaratorScope(S, SS);
995}
996
997/// ActOnDelayedCXXMethodParameter - We've already started a delayed
998/// C++ method declaration. We're (re-)introducing the given
999/// function parameter into scope for use in parsing later parts of
1000/// the method declaration. For example, we could see an
1001/// ActOnParamDefaultArgument event for this parameter.
1002void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1003 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +00001004
1005 // If this parameter has an unparsed default argument, clear it out
1006 // to make way for the parsed default argument.
1007 if (Param->hasUnparsedDefaultArg())
1008 Param->setDefaultArg(0);
1009
Douglas Gregor72b505b2008-12-16 21:30:33 +00001010 S->AddDecl(Param);
1011 if (Param->getDeclName())
1012 IdResolver.AddDecl(Param);
1013}
1014
1015/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1016/// processing the delayed method declaration for Method. The method
1017/// declaration is now considered finished. There may be a separate
1018/// ActOnStartOfFunctionDef action later (not necessarily
1019/// immediately!) for this method, if it was also defined inside the
1020/// class body.
1021void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1022 FunctionDecl *Method = (FunctionDecl*)MethodD;
1023 CXXScopeSpec SS;
1024 SS.setScopeRep(Method->getDeclContext());
1025 ActOnCXXExitDeclaratorScope(S, SS);
1026
1027 // Now that we have our default arguments, check the constructor
1028 // again. It could produce additional diagnostics or affect whether
1029 // the class has implicitly-declared destructors, among other
1030 // things.
1031 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1032 if (CheckConstructor(Constructor))
1033 Constructor->setInvalidDecl();
1034 }
1035
1036 // Check the default arguments, which we may have added.
1037 if (!Method->isInvalidDecl())
1038 CheckCXXDefaultArguments(Method);
1039}
1040
Douglas Gregor42a552f2008-11-05 20:51:48 +00001041/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001042/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001043/// R. If there are any errors in the declarator, this routine will
1044/// emit diagnostics and return true. Otherwise, it will return
1045/// false. Either way, the type @p R will be updated to reflect a
1046/// well-formed type for the constructor.
1047bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1048 FunctionDecl::StorageClass& SC) {
1049 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1050 bool isInvalid = false;
1051
1052 // C++ [class.ctor]p3:
1053 // A constructor shall not be virtual (10.3) or static (9.4). A
1054 // constructor can be invoked for a const, volatile or const
1055 // volatile object. A constructor shall not be declared const,
1056 // volatile, or const volatile (9.3.2).
1057 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001058 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1059 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1060 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001061 isInvalid = true;
1062 }
1063 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001064 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1065 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1066 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001067 isInvalid = true;
1068 SC = FunctionDecl::None;
1069 }
1070 if (D.getDeclSpec().hasTypeSpecifier()) {
1071 // Constructors don't have return types, but the parser will
1072 // happily parse something like:
1073 //
1074 // class X {
1075 // float X(float);
1076 // };
1077 //
1078 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001079 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1080 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1081 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001082 }
1083 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1084 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1085 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1087 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001088 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001089 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1090 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001091 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001092 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1093 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001094 }
1095
1096 // Rebuild the function type "R" without any type qualifiers (in
1097 // case any of the errors above fired) and with "void" as the
1098 // return type, since constructors don't have return types. We
1099 // *always* have to do this, because GetTypeForDeclarator will
1100 // put in a result type of "int" when none was specified.
1101 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1102 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1103 Proto->getNumArgs(),
1104 Proto->isVariadic(),
1105 0);
1106
1107 return isInvalid;
1108}
1109
Douglas Gregor72b505b2008-12-16 21:30:33 +00001110/// CheckConstructor - Checks a fully-formed constructor for
1111/// well-formedness, issuing any diagnostics required. Returns true if
1112/// the constructor declarator is invalid.
1113bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1114 if (Constructor->isInvalidDecl())
1115 return true;
1116
1117 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1118 bool Invalid = false;
1119
1120 // C++ [class.copy]p3:
1121 // A declaration of a constructor for a class X is ill-formed if
1122 // its first parameter is of type (optionally cv-qualified) X and
1123 // either there are no other parameters or else all other
1124 // parameters have default arguments.
1125 if ((Constructor->getNumParams() == 1) ||
1126 (Constructor->getNumParams() > 1 &&
1127 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1128 QualType ParamType = Constructor->getParamDecl(0)->getType();
1129 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1130 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1131 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1132 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1133 Invalid = true;
1134 }
1135 }
1136
1137 // Notify the class that we've added a constructor.
1138 ClassDecl->addedConstructor(Context, Constructor);
1139
1140 return Invalid;
1141}
1142
Douglas Gregor42a552f2008-11-05 20:51:48 +00001143/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1144/// the well-formednes of the destructor declarator @p D with type @p
1145/// R. If there are any errors in the declarator, this routine will
1146/// emit diagnostics and return true. Otherwise, it will return
1147/// false. Either way, the type @p R will be updated to reflect a
1148/// well-formed type for the destructor.
1149bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1150 FunctionDecl::StorageClass& SC) {
1151 bool isInvalid = false;
1152
1153 // C++ [class.dtor]p1:
1154 // [...] A typedef-name that names a class is a class-name
1155 // (7.1.3); however, a typedef-name that names a class shall not
1156 // be used as the identifier in the declarator for a destructor
1157 // declaration.
1158 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1159 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001160 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001161 << TypedefD->getDeclName();
Douglas Gregor55c60952008-11-10 14:41:22 +00001162 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001163 }
1164
1165 // C++ [class.dtor]p2:
1166 // A destructor is used to destroy objects of its class type. A
1167 // destructor takes no parameters, and no return type can be
1168 // specified for it (not even void). The address of a destructor
1169 // shall not be taken. A destructor shall not be static. A
1170 // destructor can be invoked for a const, volatile or const
1171 // volatile object. A destructor shall not be declared const,
1172 // volatile or const volatile (9.3.2).
1173 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001174 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1175 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1176 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001177 isInvalid = true;
1178 SC = FunctionDecl::None;
1179 }
1180 if (D.getDeclSpec().hasTypeSpecifier()) {
1181 // Destructors don't have return types, but the parser will
1182 // happily parse something like:
1183 //
1184 // class X {
1185 // float ~X();
1186 // };
1187 //
1188 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001189 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1190 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1191 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001192 }
1193 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1194 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1195 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001196 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1197 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001198 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001199 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1200 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001201 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001202 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1203 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001204 }
1205
1206 // Make sure we don't have any parameters.
1207 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1208 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1209
1210 // Delete the parameters.
1211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1212 if (FTI.NumArgs) {
1213 delete [] FTI.ArgInfo;
1214 FTI.NumArgs = 0;
1215 FTI.ArgInfo = 0;
1216 }
1217 }
1218
1219 // Make sure the destructor isn't variadic.
1220 if (R->getAsFunctionTypeProto()->isVariadic())
1221 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1222
1223 // Rebuild the function type "R" without any type qualifiers or
1224 // parameters (in case any of the errors above fired) and with
1225 // "void" as the return type, since destructors don't have return
1226 // types. We *always* have to do this, because GetTypeForDeclarator
1227 // will put in a result type of "int" when none was specified.
1228 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1229
1230 return isInvalid;
1231}
1232
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001233/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1234/// well-formednes of the conversion function declarator @p D with
1235/// type @p R. If there are any errors in the declarator, this routine
1236/// will emit diagnostics and return true. Otherwise, it will return
1237/// false. Either way, the type @p R will be updated to reflect a
1238/// well-formed type for the conversion operator.
1239bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1240 FunctionDecl::StorageClass& SC) {
1241 bool isInvalid = false;
1242
1243 // C++ [class.conv.fct]p1:
1244 // Neither parameter types nor return type can be specified. The
1245 // type of a conversion function (8.3.5) is “function taking no
1246 // parameter returning conversion-type-id.”
1247 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001248 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1249 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1250 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001251 isInvalid = true;
1252 SC = FunctionDecl::None;
1253 }
1254 if (D.getDeclSpec().hasTypeSpecifier()) {
1255 // Conversion functions don't have return types, but the parser will
1256 // happily parse something like:
1257 //
1258 // class X {
1259 // float operator bool();
1260 // };
1261 //
1262 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001263 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1264 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1265 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001266 }
1267
1268 // Make sure we don't have any parameters.
1269 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1270 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1271
1272 // Delete the parameters.
1273 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1274 if (FTI.NumArgs) {
1275 delete [] FTI.ArgInfo;
1276 FTI.NumArgs = 0;
1277 FTI.ArgInfo = 0;
1278 }
1279 }
1280
1281 // Make sure the conversion function isn't variadic.
1282 if (R->getAsFunctionTypeProto()->isVariadic())
1283 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1284
1285 // C++ [class.conv.fct]p4:
1286 // The conversion-type-id shall not represent a function type nor
1287 // an array type.
1288 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1289 if (ConvType->isArrayType()) {
1290 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1291 ConvType = Context.getPointerType(ConvType);
1292 } else if (ConvType->isFunctionType()) {
1293 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1294 ConvType = Context.getPointerType(ConvType);
1295 }
1296
1297 // Rebuild the function type "R" without any parameters (in case any
1298 // of the errors above fired) and with the conversion type as the
1299 // return type.
1300 R = Context.getFunctionType(ConvType, 0, 0, false,
1301 R->getAsFunctionTypeProto()->getTypeQuals());
1302
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001303 // C++0x explicit conversion operators.
1304 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1305 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1306 diag::warn_explicit_conversion_functions)
1307 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1308
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001309 return isInvalid;
1310}
1311
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001312/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1313/// the declaration of the given C++ conversion function. This routine
1314/// is responsible for recording the conversion function in the C++
1315/// class, if possible.
1316Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1317 assert(Conversion && "Expected to receive a conversion function declaration");
1318
Douglas Gregor9d350972008-12-12 08:25:50 +00001319 // Set the lexical context of this conversion function
1320 Conversion->setLexicalDeclContext(CurContext);
1321
1322 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001323
1324 // Make sure we aren't redeclaring the conversion function.
1325 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001326
1327 // C++ [class.conv.fct]p1:
1328 // [...] A conversion function is never used to convert a
1329 // (possibly cv-qualified) object to the (possibly cv-qualified)
1330 // same object type (or a reference to it), to a (possibly
1331 // cv-qualified) base class of that type (or a reference to it),
1332 // or to (possibly cv-qualified) void.
1333 // FIXME: Suppress this warning if the conversion function ends up
1334 // being a virtual function that overrides a virtual function in a
1335 // base class.
1336 QualType ClassType
1337 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1338 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1339 ConvType = ConvTypeRef->getPointeeType();
1340 if (ConvType->isRecordType()) {
1341 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1342 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001343 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001344 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001345 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001346 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001347 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001348 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001349 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001350 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001351 }
1352
Douglas Gregor70316a02008-12-26 15:00:45 +00001353 if (Conversion->getPreviousDeclaration()) {
1354 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1355 for (OverloadedFunctionDecl::function_iterator
1356 Conv = Conversions->function_begin(),
1357 ConvEnd = Conversions->function_end();
1358 Conv != ConvEnd; ++Conv) {
1359 if (*Conv == Conversion->getPreviousDeclaration()) {
1360 *Conv = Conversion;
1361 return (DeclTy *)Conversion;
1362 }
1363 }
1364 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1365 } else
1366 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001367
1368 return (DeclTy *)Conversion;
1369}
1370
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001371//===----------------------------------------------------------------------===//
1372// Namespace Handling
1373//===----------------------------------------------------------------------===//
1374
1375/// ActOnStartNamespaceDef - This is called at the start of a namespace
1376/// definition.
1377Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1378 SourceLocation IdentLoc,
1379 IdentifierInfo *II,
1380 SourceLocation LBrace) {
1381 NamespaceDecl *Namespc =
1382 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1383 Namespc->setLBracLoc(LBrace);
1384
1385 Scope *DeclRegionScope = NamespcScope->getParent();
1386
1387 if (II) {
1388 // C++ [namespace.def]p2:
1389 // The identifier in an original-namespace-definition shall not have been
1390 // previously defined in the declarative region in which the
1391 // original-namespace-definition appears. The identifier in an
1392 // original-namespace-definition is the name of the namespace. Subsequently
1393 // in that declarative region, it is treated as an original-namespace-name.
1394
1395 Decl *PrevDecl =
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001396 LookupDecl(II, Decl::IDNS_Ordinary, DeclRegionScope, 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00001397 /*enableLazyBuiltinCreation=*/false,
1398 /*LookupInParent=*/false);
1399
1400 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1401 // This is an extended namespace definition.
1402 // Attach this namespace decl to the chain of extended namespace
1403 // definitions.
1404 OrigNS->setNextNamespace(Namespc);
1405 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001406
Douglas Gregor44b43212008-12-11 16:49:14 +00001407 // Remove the previous declaration from the scope.
1408 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001409 IdResolver.RemoveDecl(OrigNS);
1410 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001411 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001412 } else if (PrevDecl) {
1413 // This is an invalid name redefinition.
1414 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1415 << Namespc->getDeclName();
1416 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1417 Namespc->setInvalidDecl();
1418 // Continue on to push Namespc as current DeclContext and return it.
1419 }
1420
1421 PushOnScopeChains(Namespc, DeclRegionScope);
1422 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001423 // FIXME: Handle anonymous namespaces
1424 }
1425
1426 // Although we could have an invalid decl (i.e. the namespace name is a
1427 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001428 // FIXME: We should be able to push Namespc here, so that the
1429 // each DeclContext for the namespace has the declarations
1430 // that showed up in that particular namespace definition.
1431 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001432 return Namespc;
1433}
1434
1435/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1436/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1437void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1438 Decl *Dcl = static_cast<Decl *>(D);
1439 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1440 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1441 Namespc->setRBracLoc(RBrace);
1442 PopDeclContext();
1443}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001444
Douglas Gregorf780abc2008-12-30 03:27:21 +00001445Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1446 SourceLocation UsingLoc,
1447 SourceLocation NamespcLoc,
1448 const CXXScopeSpec &SS,
1449 SourceLocation IdentLoc,
1450 IdentifierInfo *NamespcName,
1451 AttributeList *AttrList) {
1452 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1453 assert(NamespcName && "Invalid NamespcName.");
1454 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1455
1456 // FIXME: This still requires lot more checks, and AST support.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001457
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001458 // Lookup namespace name.
1459 LookupCriteria Criteria(LookupCriteria::Namespace, /*RedeclarationOnly=*/false,
1460 /*CPlusPlus=*/true);
1461 Decl *NS = 0;
1462 if (SS.isSet())
1463 NS = LookupQualifiedName(static_cast<DeclContext*>(SS.getScopeRep()),
1464 NamespcName, Criteria);
1465 else
1466 NS = LookupName(S, NamespcName, Criteria);
1467
1468 if (NS) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001469 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1470 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001471 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001472 }
1473
1474 // FIXME: We ignore AttrList for now, and delete it to avoid leak.
1475 delete AttrList;
1476 return 0;
1477}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001478
1479/// AddCXXDirectInitializerToDecl - This action is called immediately after
1480/// ActOnDeclarator, when a C++ direct initializer is present.
1481/// e.g: "int x(1);"
1482void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1483 ExprTy **ExprTys, unsigned NumExprs,
1484 SourceLocation *CommaLocs,
1485 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001486 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001487 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001488
1489 // If there is no declaration, there was an error parsing it. Just ignore
1490 // the initializer.
1491 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001492 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001493 delete static_cast<Expr *>(ExprTys[i]);
1494 return;
1495 }
1496
1497 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1498 if (!VDecl) {
1499 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1500 RealDecl->setInvalidDecl();
1501 return;
1502 }
1503
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001504 // We will treat direct-initialization as a copy-initialization:
1505 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001506 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1507 //
1508 // Clients that want to distinguish between the two forms, can check for
1509 // direct initializer using VarDecl::hasCXXDirectInitializer().
1510 // A major benefit is that clients that don't particularly care about which
1511 // exactly form was it (like the CodeGen) can handle both cases without
1512 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001513
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001514 // C++ 8.5p11:
1515 // The form of initialization (using parentheses or '=') is generally
1516 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001517 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001518 QualType DeclInitType = VDecl->getType();
1519 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1520 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001521
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001522 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001523 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001524 = PerformInitializationByConstructor(DeclInitType,
1525 (Expr **)ExprTys, NumExprs,
1526 VDecl->getLocation(),
1527 SourceRange(VDecl->getLocation(),
1528 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001529 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001530 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001531 if (!Constructor) {
1532 RealDecl->setInvalidDecl();
1533 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001534
1535 // Let clients know that initialization was done with a direct
1536 // initializer.
1537 VDecl->setCXXDirectInitializer(true);
1538
1539 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1540 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001541 return;
1542 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001543
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001544 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001545 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1546 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001547 RealDecl->setInvalidDecl();
1548 return;
1549 }
1550
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001551 // Let clients know that initialization was done with a direct initializer.
1552 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001553
1554 assert(NumExprs == 1 && "Expected 1 expression");
1555 // Set the init expression, handles conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001556 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001557}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001558
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001559/// PerformInitializationByConstructor - Perform initialization by
1560/// constructor (C++ [dcl.init]p14), which may occur as part of
1561/// direct-initialization or copy-initialization. We are initializing
1562/// an object of type @p ClassType with the given arguments @p
1563/// Args. @p Loc is the location in the source code where the
1564/// initializer occurs (e.g., a declaration, member initializer,
1565/// functional cast, etc.) while @p Range covers the whole
1566/// initialization. @p InitEntity is the entity being initialized,
1567/// which may by the name of a declaration or a type. @p Kind is the
1568/// kind of initialization we're performing, which affects whether
1569/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001570/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001571/// when the initialization fails, emits a diagnostic and returns
1572/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001573CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001574Sema::PerformInitializationByConstructor(QualType ClassType,
1575 Expr **Args, unsigned NumArgs,
1576 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001577 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001578 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001579 const RecordType *ClassRec = ClassType->getAsRecordType();
1580 assert(ClassRec && "Can only initialize a class type here");
1581
1582 // C++ [dcl.init]p14:
1583 //
1584 // If the initialization is direct-initialization, or if it is
1585 // copy-initialization where the cv-unqualified version of the
1586 // source type is the same class as, or a derived class of, the
1587 // class of the destination, constructors are considered. The
1588 // applicable constructors are enumerated (13.3.1.3), and the
1589 // best one is chosen through overload resolution (13.3). The
1590 // constructor so selected is called to initialize the object,
1591 // with the initializer expression(s) as its argument(s). If no
1592 // constructor applies, or the overload resolution is ambiguous,
1593 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001594 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1595 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001596
1597 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001598 DeclarationName ConstructorName
1599 = Context.DeclarationNames.getCXXConstructorName(
1600 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001601 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001602 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001603 Con != ConEnd; ++Con) {
1604 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001605 if ((Kind == IK_Direct) ||
1606 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1607 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1608 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1609 }
1610
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001611 // FIXME: When we decide not to synthesize the implicitly-declared
1612 // constructors, we'll need to make them appear here.
1613
Douglas Gregor18fe5682008-11-03 20:45:27 +00001614 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001615 switch (BestViableFunction(CandidateSet, Best)) {
1616 case OR_Success:
1617 // We found a constructor. Return it.
1618 return cast<CXXConstructorDecl>(Best->Function);
1619
1620 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001621 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1622 << InitEntity << (unsigned)CandidateSet.size() << Range;
1623 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001624 return 0;
1625
1626 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001627 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001628 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1629 return 0;
1630 }
1631
1632 return 0;
1633}
1634
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001635/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1636/// determine whether they are reference-related,
1637/// reference-compatible, reference-compatible with added
1638/// qualification, or incompatible, for use in C++ initialization by
1639/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1640/// type, and the first type (T1) is the pointee type of the reference
1641/// type being initialized.
1642Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001643Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1644 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001645 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1646 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1647
1648 T1 = Context.getCanonicalType(T1);
1649 T2 = Context.getCanonicalType(T2);
1650 QualType UnqualT1 = T1.getUnqualifiedType();
1651 QualType UnqualT2 = T2.getUnqualifiedType();
1652
1653 // C++ [dcl.init.ref]p4:
1654 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1655 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1656 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001657 if (UnqualT1 == UnqualT2)
1658 DerivedToBase = false;
1659 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1660 DerivedToBase = true;
1661 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001662 return Ref_Incompatible;
1663
1664 // At this point, we know that T1 and T2 are reference-related (at
1665 // least).
1666
1667 // C++ [dcl.init.ref]p4:
1668 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1669 // reference-related to T2 and cv1 is the same cv-qualification
1670 // as, or greater cv-qualification than, cv2. For purposes of
1671 // overload resolution, cases for which cv1 is greater
1672 // cv-qualification than cv2 are identified as
1673 // reference-compatible with added qualification (see 13.3.3.2).
1674 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1675 return Ref_Compatible;
1676 else if (T1.isMoreQualifiedThan(T2))
1677 return Ref_Compatible_With_Added_Qualification;
1678 else
1679 return Ref_Related;
1680}
1681
1682/// CheckReferenceInit - Check the initialization of a reference
1683/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1684/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001685/// list), and DeclType is the type of the declaration. When ICS is
1686/// non-null, this routine will compute the implicit conversion
1687/// sequence according to C++ [over.ics.ref] and will not produce any
1688/// diagnostics; when ICS is null, it will emit diagnostics when any
1689/// errors are found. Either way, a return value of true indicates
1690/// that there was a failure, a return value of false indicates that
1691/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001692///
1693/// When @p SuppressUserConversions, user-defined conversions are
1694/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001695/// When @p AllowExplicit, we also permit explicit user-defined
1696/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001697bool
1698Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001699 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001700 bool SuppressUserConversions,
1701 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001702 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1703
1704 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1705 QualType T2 = Init->getType();
1706
Douglas Gregor904eed32008-11-10 20:40:00 +00001707 // If the initializer is the address of an overloaded function, try
1708 // to resolve the overloaded function. If all goes well, T2 is the
1709 // type of the resulting function.
1710 if (T2->isOverloadType()) {
1711 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1712 ICS != 0);
1713 if (Fn) {
1714 // Since we're performing this reference-initialization for
1715 // real, update the initializer with the resulting function.
1716 if (!ICS)
1717 FixOverloadedFunctionReference(Init, Fn);
1718
1719 T2 = Fn->getType();
1720 }
1721 }
1722
Douglas Gregor15da57e2008-10-29 02:00:59 +00001723 // Compute some basic properties of the types and the initializer.
1724 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001725 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001726 ReferenceCompareResult RefRelationship
1727 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1728
1729 // Most paths end in a failed conversion.
1730 if (ICS)
1731 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001732
1733 // C++ [dcl.init.ref]p5:
1734 // A reference to type “cv1 T1” is initialized by an expression
1735 // of type “cv2 T2” as follows:
1736
1737 // -- If the initializer expression
1738
1739 bool BindsDirectly = false;
1740 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1741 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001742 //
1743 // Note that the bit-field check is skipped if we are just computing
1744 // the implicit conversion sequence (C++ [over.best.ics]p2).
1745 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1746 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001747 BindsDirectly = true;
1748
Douglas Gregor15da57e2008-10-29 02:00:59 +00001749 if (ICS) {
1750 // C++ [over.ics.ref]p1:
1751 // When a parameter of reference type binds directly (8.5.3)
1752 // to an argument expression, the implicit conversion sequence
1753 // is the identity conversion, unless the argument expression
1754 // has a type that is a derived class of the parameter type,
1755 // in which case the implicit conversion sequence is a
1756 // derived-to-base Conversion (13.3.3.1).
1757 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1758 ICS->Standard.First = ICK_Identity;
1759 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1760 ICS->Standard.Third = ICK_Identity;
1761 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1762 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001763 ICS->Standard.ReferenceBinding = true;
1764 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001765
1766 // Nothing more to do: the inaccessibility/ambiguity check for
1767 // derived-to-base conversions is suppressed when we're
1768 // computing the implicit conversion sequence (C++
1769 // [over.best.ics]p2).
1770 return false;
1771 } else {
1772 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001773 // FIXME: Binding to a subobject of the lvalue is going to require
1774 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001775 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001776 }
1777 }
1778
1779 // -- has a class type (i.e., T2 is a class type) and can be
1780 // implicitly converted to an lvalue of type “cv3 T3,”
1781 // where “cv1 T1” is reference-compatible with “cv3 T3”
1782 // 92) (this conversion is selected by enumerating the
1783 // applicable conversion functions (13.3.1.6) and choosing
1784 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001785 if (!SuppressUserConversions && T2->isRecordType()) {
1786 // FIXME: Look for conversions in base classes!
1787 CXXRecordDecl *T2RecordDecl
1788 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001789
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001790 OverloadCandidateSet CandidateSet;
1791 OverloadedFunctionDecl *Conversions
1792 = T2RecordDecl->getConversionFunctions();
1793 for (OverloadedFunctionDecl::function_iterator Func
1794 = Conversions->function_begin();
1795 Func != Conversions->function_end(); ++Func) {
1796 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1797
1798 // If the conversion function doesn't return a reference type,
1799 // it can't be considered for this conversion.
1800 // FIXME: This will change when we support rvalue references.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001801 if (Conv->getConversionType()->isReferenceType() &&
1802 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001803 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1804 }
1805
1806 OverloadCandidateSet::iterator Best;
1807 switch (BestViableFunction(CandidateSet, Best)) {
1808 case OR_Success:
1809 // This is a direct binding.
1810 BindsDirectly = true;
1811
1812 if (ICS) {
1813 // C++ [over.ics.ref]p1:
1814 //
1815 // [...] If the parameter binds directly to the result of
1816 // applying a conversion function to the argument
1817 // expression, the implicit conversion sequence is a
1818 // user-defined conversion sequence (13.3.3.1.2), with the
1819 // second standard conversion sequence either an identity
1820 // conversion or, if the conversion function returns an
1821 // entity of a type that is a derived class of the parameter
1822 // type, a derived-to-base Conversion.
1823 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1824 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1825 ICS->UserDefined.After = Best->FinalConversion;
1826 ICS->UserDefined.ConversionFunction = Best->Function;
1827 assert(ICS->UserDefined.After.ReferenceBinding &&
1828 ICS->UserDefined.After.DirectBinding &&
1829 "Expected a direct reference binding!");
1830 return false;
1831 } else {
1832 // Perform the conversion.
1833 // FIXME: Binding to a subobject of the lvalue is going to require
1834 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001835 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001836 }
1837 break;
1838
1839 case OR_Ambiguous:
1840 assert(false && "Ambiguous reference binding conversions not implemented.");
1841 return true;
1842
1843 case OR_No_Viable_Function:
1844 // There was no suitable conversion; continue with other checks.
1845 break;
1846 }
1847 }
1848
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001849 if (BindsDirectly) {
1850 // C++ [dcl.init.ref]p4:
1851 // [...] In all cases where the reference-related or
1852 // reference-compatible relationship of two types is used to
1853 // establish the validity of a reference binding, and T1 is a
1854 // base class of T2, a program that necessitates such a binding
1855 // is ill-formed if T1 is an inaccessible (clause 11) or
1856 // ambiguous (10.2) base class of T2.
1857 //
1858 // Note that we only check this condition when we're allowed to
1859 // complain about errors, because we should not be checking for
1860 // ambiguity (or inaccessibility) unless the reference binding
1861 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001862 if (DerivedToBase)
1863 return CheckDerivedToBaseConversion(T2, T1,
1864 Init->getSourceRange().getBegin(),
1865 Init->getSourceRange());
1866 else
1867 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001868 }
1869
1870 // -- Otherwise, the reference shall be to a non-volatile const
1871 // type (i.e., cv1 shall be const).
1872 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001873 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001874 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001875 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001876 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1877 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001878 return true;
1879 }
1880
1881 // -- If the initializer expression is an rvalue, with T2 a
1882 // class type, and “cv1 T1” is reference-compatible with
1883 // “cv2 T2,” the reference is bound in one of the
1884 // following ways (the choice is implementation-defined):
1885 //
1886 // -- The reference is bound to the object represented by
1887 // the rvalue (see 3.10) or to a sub-object within that
1888 // object.
1889 //
1890 // -- A temporary of type “cv1 T2” [sic] is created, and
1891 // a constructor is called to copy the entire rvalue
1892 // object into the temporary. The reference is bound to
1893 // the temporary or to a sub-object within the
1894 // temporary.
1895 //
1896 //
1897 // The constructor that would be used to make the copy
1898 // shall be callable whether or not the copy is actually
1899 // done.
1900 //
1901 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1902 // freedom, so we will always take the first option and never build
1903 // a temporary in this case. FIXME: We will, however, have to check
1904 // for the presence of a copy constructor in C++98/03 mode.
1905 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001906 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1907 if (ICS) {
1908 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1909 ICS->Standard.First = ICK_Identity;
1910 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1911 ICS->Standard.Third = ICK_Identity;
1912 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1913 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001914 ICS->Standard.ReferenceBinding = true;
1915 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001916 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001917 // FIXME: Binding to a subobject of the rvalue is going to require
1918 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001919 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001920 }
1921 return false;
1922 }
1923
1924 // -- Otherwise, a temporary of type “cv1 T1” is created and
1925 // initialized from the initializer expression using the
1926 // rules for a non-reference copy initialization (8.5). The
1927 // reference is then bound to the temporary. If T1 is
1928 // reference-related to T2, cv1 must be the same
1929 // cv-qualification as, or greater cv-qualification than,
1930 // cv2; otherwise, the program is ill-formed.
1931 if (RefRelationship == Ref_Related) {
1932 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1933 // we would be reference-compatible or reference-compatible with
1934 // added qualification. But that wasn't the case, so the reference
1935 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001936 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001937 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001938 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001939 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1940 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001941 return true;
1942 }
1943
1944 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001945 if (ICS) {
1946 /// C++ [over.ics.ref]p2:
1947 ///
1948 /// When a parameter of reference type is not bound directly to
1949 /// an argument expression, the conversion sequence is the one
1950 /// required to convert the argument expression to the
1951 /// underlying type of the reference according to
1952 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1953 /// to copy-initializing a temporary of the underlying type with
1954 /// the argument expression. Any difference in top-level
1955 /// cv-qualification is subsumed by the initialization itself
1956 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001957 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001958 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1959 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00001960 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00001961 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001962}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001963
1964/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1965/// of this overloaded operator is well-formed. If so, returns false;
1966/// otherwise, emits appropriate diagnostics and returns true.
1967bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001968 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001969 "Expected an overloaded operator declaration");
1970
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001971 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1972
1973 // C++ [over.oper]p5:
1974 // The allocation and deallocation functions, operator new,
1975 // operator new[], operator delete and operator delete[], are
1976 // described completely in 3.7.3. The attributes and restrictions
1977 // found in the rest of this subclause do not apply to them unless
1978 // explicitly stated in 3.7.3.
1979 // FIXME: Write a separate routine for checking this. For now, just
1980 // allow it.
1981 if (Op == OO_New || Op == OO_Array_New ||
1982 Op == OO_Delete || Op == OO_Array_Delete)
1983 return false;
1984
1985 // C++ [over.oper]p6:
1986 // An operator function shall either be a non-static member
1987 // function or be a non-member function and have at least one
1988 // parameter whose type is a class, a reference to a class, an
1989 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001990 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1991 if (MethodDecl->isStatic())
1992 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001993 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001994 } else {
1995 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001996 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1997 ParamEnd = FnDecl->param_end();
1998 Param != ParamEnd; ++Param) {
1999 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002000 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2001 ClassOrEnumParam = true;
2002 break;
2003 }
2004 }
2005
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002006 if (!ClassOrEnumParam)
2007 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002008 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002009 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002010 }
2011
2012 // C++ [over.oper]p8:
2013 // An operator function cannot have default arguments (8.3.6),
2014 // except where explicitly stated below.
2015 //
2016 // Only the function-call operator allows default arguments
2017 // (C++ [over.call]p1).
2018 if (Op != OO_Call) {
2019 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2020 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002021 if ((*Param)->hasUnparsedDefaultArg())
2022 return Diag((*Param)->getLocation(),
2023 diag::err_operator_overload_default_arg)
2024 << FnDecl->getDeclName();
2025 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002026 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002027 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002028 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002029 }
2030 }
2031
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002032 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2033 { false, false, false }
2034#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2035 , { Unary, Binary, MemberOnly }
2036#include "clang/Basic/OperatorKinds.def"
2037 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002038
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002039 bool CanBeUnaryOperator = OperatorUses[Op][0];
2040 bool CanBeBinaryOperator = OperatorUses[Op][1];
2041 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002042
2043 // C++ [over.oper]p8:
2044 // [...] Operator functions cannot have more or fewer parameters
2045 // than the number required for the corresponding operator, as
2046 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002047 unsigned NumParams = FnDecl->getNumParams()
2048 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002049 if (Op != OO_Call &&
2050 ((NumParams == 1 && !CanBeUnaryOperator) ||
2051 (NumParams == 2 && !CanBeBinaryOperator) ||
2052 (NumParams < 1) || (NumParams > 2))) {
2053 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002054 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002055 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002056 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002057 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002058 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002059 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002060 assert(CanBeBinaryOperator &&
2061 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002062 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002063 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002064
Chris Lattner416e46f2008-11-21 07:57:12 +00002065 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002066 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002067 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002068
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002069 // Overloaded operators other than operator() cannot be variadic.
2070 if (Op != OO_Call &&
2071 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002072 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002073 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002074 }
2075
2076 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002077 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2078 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002079 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002080 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002081 }
2082
2083 // C++ [over.inc]p1:
2084 // The user-defined function called operator++ implements the
2085 // prefix and postfix ++ operator. If this function is a member
2086 // function with no parameters, or a non-member function with one
2087 // parameter of class or enumeration type, it defines the prefix
2088 // increment operator ++ for objects of that type. If the function
2089 // is a member function with one parameter (which shall be of type
2090 // int) or a non-member function with two parameters (the second
2091 // of which shall be of type int), it defines the postfix
2092 // increment operator ++ for objects of that type.
2093 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2094 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2095 bool ParamIsInt = false;
2096 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2097 ParamIsInt = BT->getKind() == BuiltinType::Int;
2098
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002099 if (!ParamIsInt)
2100 return Diag(LastParam->getLocation(),
2101 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002102 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002103 }
2104
Sebastian Redl64b45f72009-01-05 20:52:13 +00002105 // Notify the class if it got an assignment operator.
2106 if (Op == OO_Equal) {
2107 // Would have returned earlier otherwise.
2108 assert(isa<CXXMethodDecl>(FnDecl) &&
2109 "Overloaded = not member, but not filtered.");
2110 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2111 Method->getParent()->addedAssignmentOperator(Context, Method);
2112 }
2113
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002114 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002115}
Chris Lattner5a003a42008-12-17 07:09:26 +00002116
Douglas Gregor074149e2009-01-05 19:45:36 +00002117/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2118/// linkage specification, including the language and (if present)
2119/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2120/// the location of the language string literal, which is provided
2121/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2122/// the '{' brace. Otherwise, this linkage specification does not
2123/// have any braces.
2124Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2125 SourceLocation ExternLoc,
2126 SourceLocation LangLoc,
2127 const char *Lang,
2128 unsigned StrSize,
2129 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002130 LinkageSpecDecl::LanguageIDs Language;
2131 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2132 Language = LinkageSpecDecl::lang_c;
2133 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2134 Language = LinkageSpecDecl::lang_cxx;
2135 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002136 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002137 return 0;
2138 }
2139
2140 // FIXME: Add all the various semantics of linkage specifications
2141
Douglas Gregor074149e2009-01-05 19:45:36 +00002142 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2143 LangLoc, Language,
2144 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002145 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002146 PushDeclContext(S, D);
2147 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002148}
2149
Douglas Gregor074149e2009-01-05 19:45:36 +00002150/// ActOnFinishLinkageSpecification - Completely the definition of
2151/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2152/// valid, it's the position of the closing '}' brace in a linkage
2153/// specification that uses braces.
2154Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2155 DeclTy *LinkageSpec,
2156 SourceLocation RBraceLoc) {
2157 if (LinkageSpec)
2158 PopDeclContext();
2159 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002160}
2161
Sebastian Redl4b07b292008-12-22 19:15:10 +00002162/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2163/// handler.
2164Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2165{
2166 QualType ExDeclType = GetTypeForDeclarator(D, S);
2167 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2168
2169 bool Invalid = false;
2170
2171 // Arrays and functions decay.
2172 if (ExDeclType->isArrayType())
2173 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2174 else if (ExDeclType->isFunctionType())
2175 ExDeclType = Context.getPointerType(ExDeclType);
2176
2177 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2178 // The exception-declaration shall not denote a pointer or reference to an
2179 // incomplete type, other than [cv] void*.
2180 QualType BaseType = ExDeclType;
2181 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2182 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2183 BaseType = Ptr->getPointeeType();
2184 Mode = 1;
2185 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2186 BaseType = Ref->getPointeeType();
2187 Mode = 2;
2188 }
2189 if ((Mode == 0 || !BaseType->isVoidType()) && BaseType->isIncompleteType()) {
2190 Invalid = true;
2191 Diag(Begin, diag::err_catch_incomplete) << BaseType << Mode;
2192 }
2193
Sebastian Redl8351da02008-12-22 21:35:02 +00002194 // FIXME: Need to test for ability to copy-construct and destroy the
2195 // exception variable.
2196 // FIXME: Need to check for abstract classes.
2197
Sebastian Redl4b07b292008-12-22 19:15:10 +00002198 IdentifierInfo *II = D.getIdentifier();
2199 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2200 // The scope should be freshly made just for us. There is just no way
2201 // it contains any previous declaration.
2202 assert(!S->isDeclScope(PrevDecl));
2203 if (PrevDecl->isTemplateParameter()) {
2204 // Maybe we will complain about the shadowed template parameter.
2205 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2206
2207 }
2208 }
2209
2210 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2211 II, ExDeclType, VarDecl::None, 0, Begin);
2212 if (D.getInvalidType() || Invalid)
2213 ExDecl->setInvalidDecl();
2214
2215 if (D.getCXXScopeSpec().isSet()) {
2216 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2217 << D.getCXXScopeSpec().getRange();
2218 ExDecl->setInvalidDecl();
2219 }
2220
2221 // Add the exception declaration into this scope.
2222 S->AddDecl(ExDecl);
2223 if (II)
2224 IdResolver.AddDecl(ExDecl);
2225
2226 ProcessDeclAttributes(ExDecl, D);
2227 return ExDecl;
2228}