blob: 95f920063d21312822746e95f00427a0bc2bba1c [file] [log] [blame]
Chris Lattnerac7b83a2008-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 Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000026#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner97316c02008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattnerb1856db2008-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 Lattnerd5a56aa2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000044
Chris Lattnerb1856db2008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000048
Chris Lattnerb1856db2008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000052 };
Chris Lattner97316c02008-04-10 02:22:51 +000053
Chris Lattnerb1856db2008-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 Lattnerd5a56aa2008-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 Lattnerb1856db2008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000061 }
62
Chris Lattnerb1856db2008-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 Gregord2baafd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-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 Lattner8ba580c2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000088 }
Chris Lattner97316c02008-04-10 02:22:51 +000089
Douglas Gregor3c246952008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000092
Douglas Gregora5b022a2008-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 Lattner8ba580c2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000101 }
Chris Lattner97316c02008-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 Lattnerac7b83a2008-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 Lattner8ba580c2008-11-19 05:08:23 +0000116 Diag(EqualLoc, diag::err_param_default_argument)
117 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000118 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-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 Lattnerac7b83a2008-04-08 05:04:30 +0000128 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000129 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
130 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000131 Param->getDeclName(),
132 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000133 if (DefaultArgPtr != DefaultArg.get()) {
134 DefaultArg.take();
135 DefaultArg.reset(DefaultArgPtr);
136 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000137 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000138 return;
139 }
140
Chris Lattner97316c02008-04-10 02:22:51 +0000141 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000142 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000143 if (DefaultArgChecker.Visit(DefaultArg.get())) {
144 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000145 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000146 }
Chris Lattner97316c02008-04-10 02:22:51 +0000147
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000148 // Okay: add the default argument to the parameter
149 Param->setDefaultArg(DefaultArg.take());
150}
151
Douglas Gregor62ae25a2008-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 Gregor605de8d2008-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 Gregor2b9422f2008-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 Gregor62ae25a2008-12-24 00:01:03 +0000187 if (Param->hasUnparsedDefaultArg()) {
188 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-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 Gregor62ae25a2008-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 Gregor2b9422f2008-05-07 04:49:29 +0000197 }
198 }
199 }
200 }
201}
202
Chris Lattnerac7b83a2008-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 Lattner8ba580c2008-11-19 05:08:23 +0000227 diag::err_param_default_argument_redefinition)
228 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000229 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattnerac7b83a2008-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 Gregor605de8d2008-12-16 21:30:33 +0000263 if (Param->isInvalidDecl())
264 /* We already complained about this parameter. */;
265 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000266 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000267 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000268 << Param->getIdentifier();
Chris Lattnerac7b83a2008-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 Gregor62ae25a2008-12-24 00:01:03 +0000285 if (!Param->hasUnparsedDefaultArg())
286 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000287 Param->setDefaultArg(0);
288 }
289 }
290 }
291}
Douglas Gregorec93f442008-04-13 21:30:24 +0000292
Douglas Gregorf15ac4b2008-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.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000297bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
298 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-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 Gregorf15ac4b2008-10-31 09:07:45 +0000307 return &II == CurDecl->getIdentifier();
308 else
309 return false;
310}
311
Douglas Gregorec93f442008-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 Gregorabed2172008-10-22 17:49:05 +0000317Sema::BaseResult
318Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
319 bool Virtual, AccessSpecifier Access,
320 TypeTy *basetype, SourceLocation BaseLoc) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000321 CXXRecordDecl *Decl = (CXXRecordDecl*)classdecl;
Douglas Gregorec93f442008-04-13 21:30:24 +0000322 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
323
324 // Base specifiers must be record types.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000325 if (!BaseType->isRecordType())
326 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000327
328 // C++ [class.union]p1:
329 // A union shall not be used as a base class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000330 if (BaseType->isUnionType())
331 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000332
333 // C++ [class.union]p1:
334 // A union shall not have base classes.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000335 if (Decl->isUnion())
336 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
337 << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000338
339 // C++ [class.derived]p2:
340 // The class-name in a base-specifier shall not be an incompletely
341 // defined class.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000342 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
343 SpecifierRange))
344 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000345
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000346 // If the base class is polymorphic, the new one is, too.
347 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
348 assert(BaseDecl && "Record type has no declaration");
349 BaseDecl = BaseDecl->getDefinition(Context);
350 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattner8ba580c2008-11-19 05:08:23 +0000351 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000352 Decl->setPolymorphic(true);
353
354 // C++ [dcl.init.aggr]p1:
355 // An aggregate is [...] a class with [...] no base classes [...].
356 Decl->setAggregate(false);
357 Decl->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000358
Douglas Gregorabed2172008-10-22 17:49:05 +0000359 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000360 return new CXXBaseSpecifier(SpecifierRange, Virtual,
361 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000362}
Douglas Gregorec93f442008-04-13 21:30:24 +0000363
Douglas Gregorabed2172008-10-22 17:49:05 +0000364/// ActOnBaseSpecifiers - Attach the given base specifiers to the
365/// class, after checking whether there are any duplicate base
366/// classes.
367void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
368 unsigned NumBases) {
369 if (NumBases == 0)
370 return;
371
372 // Used to keep track of which base types we have already seen, so
373 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000374 // that the key is always the unqualified canonical type of the base
375 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000376 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
377
378 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000379 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
380 unsigned NumGoodBases = 0;
381 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000382 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000383 = Context.getCanonicalType(BaseSpecs[idx]->getType());
384 NewBaseType = NewBaseType.getUnqualifiedType();
385
Douglas Gregorabed2172008-10-22 17:49:05 +0000386 if (KnownBaseTypes[NewBaseType]) {
387 // C++ [class.mi]p3:
388 // A class shall not be specified as a direct base class of a
389 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000390 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000391 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000392 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000393 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000394
395 // Delete the duplicate base class specifier; we're going to
396 // overwrite its pointer later.
397 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000398 } else {
399 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000400 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
401 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000402 }
403 }
404
405 // Attach the remaining base class specifiers to the derived class.
406 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000407 Decl->setBases(BaseSpecs, NumGoodBases);
408
409 // Delete the remaining (good) base class specifiers, since their
410 // data has been copied into the CXXRecordDecl.
411 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
412 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000413}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000414
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000415//===----------------------------------------------------------------------===//
416// C++ class member Handling
417//===----------------------------------------------------------------------===//
418
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000419/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
420/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
421/// bitfield width if there is one and 'InitExpr' specifies the initializer if
422/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
423/// declarators on it.
424///
Douglas Gregor605de8d2008-12-16 21:30:33 +0000425/// FIXME: The note below is out-of-date.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000426/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
427/// an instance field is declared, a new CXXFieldDecl is created but the method
428/// does *not* return it; it returns LastInGroup instead. The other C++ members
429/// (which are all ScopedDecls) are returned after appending them to
430/// LastInGroup.
431Sema::DeclTy *
432Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
433 ExprTy *BW, ExprTy *InitExpr,
434 DeclTy *LastInGroup) {
435 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000436 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000437 Expr *BitWidth = static_cast<Expr*>(BW);
438 Expr *Init = static_cast<Expr*>(InitExpr);
439 SourceLocation Loc = D.getIdentifierLoc();
440
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000441 bool isFunc = D.isFunctionDeclarator();
442
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000443 // C++ 9.2p6: A member shall not be declared to have automatic storage
444 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000445 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
446 // data members and cannot be applied to names declared const or static,
447 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000448 switch (DS.getStorageClassSpec()) {
449 case DeclSpec::SCS_unspecified:
450 case DeclSpec::SCS_typedef:
451 case DeclSpec::SCS_static:
452 // FALL THROUGH.
453 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000454 case DeclSpec::SCS_mutable:
455 if (isFunc) {
456 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000457 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000458 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000459 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
460
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000461 // FIXME: It would be nicer if the keyword was ignored only for this
462 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000463 D.getMutableDeclSpec().ClearStorageClassSpecs();
464 } else {
465 QualType T = GetTypeForDeclarator(D, S);
466 diag::kind err = static_cast<diag::kind>(0);
467 if (T->isReferenceType())
468 err = diag::err_mutable_reference;
469 else if (T.isConstQualified())
470 err = diag::err_mutable_const;
471 if (err != 0) {
472 if (DS.getStorageClassSpecLoc().isValid())
473 Diag(DS.getStorageClassSpecLoc(), err);
474 else
475 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000476 // FIXME: It would be nicer if the keyword was ignored only for this
477 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000478 D.getMutableDeclSpec().ClearStorageClassSpecs();
479 }
480 }
481 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000482 default:
483 if (DS.getStorageClassSpecLoc().isValid())
484 Diag(DS.getStorageClassSpecLoc(),
485 diag::err_storageclass_invalid_for_member);
486 else
487 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
488 D.getMutableDeclSpec().ClearStorageClassSpecs();
489 }
490
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000491 if (!isFunc &&
492 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
493 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000494 // Check also for this case:
495 //
496 // typedef int f();
497 // f a;
498 //
499 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
500 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
501 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000502
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000503 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
504 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000505 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000506
507 Decl *Member;
508 bool InvalidDecl = false;
509
510 if (isInstField)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000511 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
512 Loc, D, BitWidth));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000513 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000514 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000515
516 if (!Member) return LastInGroup;
517
Douglas Gregor6704b312008-11-17 22:58:34 +0000518 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000519
520 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
521 // specific methods. Use a wrapper class that can be used with all C++ class
522 // member decls.
523 CXXClassMemberWrapper(Member).setAccess(AS);
524
Douglas Gregor15e04622008-11-05 16:20:31 +0000525 // C++ [dcl.init.aggr]p1:
526 // An aggregate is an array or a class (clause 9) with [...] no
527 // private or protected non-static data members (clause 11).
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000528 // A POD must be an aggregate.
529 if (isInstField && (AS == AS_private || AS == AS_protected)) {
530 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
531 Record->setAggregate(false);
532 Record->setPOD(false);
533 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000534
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000535 if (DS.isVirtualSpecified()) {
536 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
537 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
538 InvalidDecl = true;
539 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000540 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000541 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
542 CurClass->setAggregate(false);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000543 CurClass->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000544 CurClass->setPolymorphic(true);
545 }
546 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000547
Sebastian Redl83faa292009-01-09 19:57:06 +0000548 // FIXME: The above definition of virtual is not sufficient. A function is
549 // also virtual if it overrides an already virtual function. This is important
550 // to do here because it decides the validity of a pure specifier.
551
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000552 if (BitWidth) {
553 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
554 // constant-expression be a value equal to zero.
555 // FIXME: Check this.
556
557 if (D.isFunctionDeclarator()) {
558 // FIXME: Emit diagnostic about only constructors taking base initializers
559 // or something similar, when constructor support is in place.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000560 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000561 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000562 InvalidDecl = true;
563
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000564 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000565 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000566 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000567 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000568 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000569 InvalidDecl = true;
570 }
571
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000572 } else if (isa<FunctionDecl>(Member)) {
573 // A function typedef ("typedef int f(); f a;").
574 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000575 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000576 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000577 InvalidDecl = true;
578
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000579 } else if (isa<TypedefDecl>(Member)) {
580 // "cannot declare 'A' to be a bit-field type"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000581 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000582 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000583 InvalidDecl = true;
584
585 } else {
586 assert(isa<CXXClassVarDecl>(Member) &&
587 "Didn't we cover all member kinds?");
588 // C++ 9.6p3: A bit-field shall not be a static member.
589 // "static member 'A' cannot be a bit-field"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000590 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000591 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000592 InvalidDecl = true;
593 }
594 }
595
596 if (Init) {
597 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
598 // if it declares a static member of const integral or const enumeration
599 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000600 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
601 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000602 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000603 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000604 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
605 CVD->getType()->isIntegralType()) {
606 // constant-initializer
607 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000608 InvalidDecl = true;
609
610 } else {
611 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000612 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000613 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000614 InvalidDecl = true;
615 }
616
617 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000618 // not static member. perhaps virtual function?
619 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redl54e4be92009-01-09 22:29:03 +0000620 // With declarators parsed the way they are, the parser cannot
621 // distinguish between a normal initializer and a pure-specifier.
622 // Thus this grotesque test.
Sebastian Redl83faa292009-01-09 19:57:06 +0000623 IntegerLiteral *IL;
624 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
625 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
626 if (MD->isVirtual())
627 MD->setPure();
628 else {
629 Diag(Loc, diag::err_non_virtual_pure)
630 << Name << Init->getSourceRange();
631 InvalidDecl = true;
632 }
633 } else {
634 Diag(Loc, diag::err_member_function_initialization)
635 << Name << Init->getSourceRange();
636 InvalidDecl = true;
637 }
638 } else {
639 Diag(Loc, diag::err_member_initialization)
640 << Name << Init->getSourceRange();
641 InvalidDecl = true;
642 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000643 }
644 }
645
646 if (InvalidDecl)
647 Member->setInvalidDecl();
648
649 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000650 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000651 return LastInGroup;
652 }
653 return Member;
654}
655
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000656/// ActOnMemInitializer - Handle a C++ member initializer.
657Sema::MemInitResult
658Sema::ActOnMemInitializer(DeclTy *ConstructorD,
659 Scope *S,
660 IdentifierInfo *MemberOrBase,
661 SourceLocation IdLoc,
662 SourceLocation LParenLoc,
663 ExprTy **Args, unsigned NumArgs,
664 SourceLocation *CommaLocs,
665 SourceLocation RParenLoc) {
666 CXXConstructorDecl *Constructor
667 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
668 if (!Constructor) {
669 // The user wrote a constructor initializer on a function that is
670 // not a C++ constructor. Ignore the error for now, because we may
671 // have more member initializers coming; we'll diagnose it just
672 // once in ActOnMemInitializers.
673 return true;
674 }
675
676 CXXRecordDecl *ClassDecl = Constructor->getParent();
677
678 // C++ [class.base.init]p2:
679 // Names in a mem-initializer-id are looked up in the scope of the
680 // constructor’s class and, if not found in that scope, are looked
681 // up in the scope containing the constructor’s
682 // definition. [Note: if the constructor’s class contains a member
683 // with the same name as a direct or virtual base class of the
684 // class, a mem-initializer-id naming the member or base class and
685 // composed of a single identifier refers to the class member. A
686 // mem-initializer-id for the hidden base class may be specified
687 // using a qualified name. ]
688 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000689 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000690 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000691 if (Result.first != Result.second)
692 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000693
694 // FIXME: Handle members of an anonymous union.
695
696 if (Member) {
697 // FIXME: Perform direct initialization of the member.
698 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
699 }
700
701 // It didn't name a member, so see if it names a class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000702 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000703 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000704 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
705 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000706
707 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
708 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000709 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000710 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000711
712 // C++ [class.base.init]p2:
713 // [...] Unless the mem-initializer-id names a nonstatic data
714 // member of the constructor’s class or a direct or virtual base
715 // of that class, the mem-initializer is ill-formed. A
716 // mem-initializer-list can initialize a base class using any
717 // name that denotes that base class type.
718
719 // First, check for a direct base class.
720 const CXXBaseSpecifier *DirectBaseSpec = 0;
721 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
722 Base != ClassDecl->bases_end(); ++Base) {
723 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
724 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
725 // We found a direct base of this type. That's what we're
726 // initializing.
727 DirectBaseSpec = &*Base;
728 break;
729 }
730 }
731
732 // Check for a virtual base class.
733 // FIXME: We might be able to short-circuit this if we know in
734 // advance that there are no virtual bases.
735 const CXXBaseSpecifier *VirtualBaseSpec = 0;
736 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
737 // We haven't found a base yet; search the class hierarchy for a
738 // virtual base class.
739 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
740 /*DetectVirtual=*/false);
741 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
742 for (BasePaths::paths_iterator Path = Paths.begin();
743 Path != Paths.end(); ++Path) {
744 if (Path->back().Base->isVirtual()) {
745 VirtualBaseSpec = Path->back().Base;
746 break;
747 }
748 }
749 }
750 }
751
752 // C++ [base.class.init]p2:
753 // If a mem-initializer-id is ambiguous because it designates both
754 // a direct non-virtual base class and an inherited virtual base
755 // class, the mem-initializer is ill-formed.
756 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000757 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
758 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000759
760 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
761}
762
763
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000764void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
765 DeclTy *TagDecl,
766 SourceLocation LBrac,
767 SourceLocation RBrac) {
768 ActOnFields(S, RLoc, TagDecl,
769 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000770 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000771 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000772}
773
Douglas Gregore640ab62008-11-03 17:51:48 +0000774/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
775/// special functions, such as the default constructor, copy
776/// constructor, or destructor, to the given C++ class (C++
777/// [special]p1). This routine can only be executed just before the
778/// definition of the class is complete.
779void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000780 QualType ClassType = Context.getTypeDeclType(ClassDecl);
781 ClassType = Context.getCanonicalType(ClassType);
782
Douglas Gregore640ab62008-11-03 17:51:48 +0000783 if (!ClassDecl->hasUserDeclaredConstructor()) {
784 // C++ [class.ctor]p5:
785 // A default constructor for a class X is a constructor of class X
786 // that can be called without an argument. If there is no
787 // user-declared constructor for class X, a default constructor is
788 // implicitly declared. An implicitly-declared default constructor
789 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000790 DeclarationName Name
791 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000792 CXXConstructorDecl *DefaultCon =
793 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000794 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000795 Context.getFunctionType(Context.VoidTy,
796 0, 0, false, 0),
797 /*isExplicit=*/false,
798 /*isInline=*/true,
799 /*isImplicitlyDeclared=*/true);
800 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000801 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000802 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000803
804 // Notify the class that we've added a constructor.
805 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000806 }
807
808 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
809 // C++ [class.copy]p4:
810 // If the class definition does not explicitly declare a copy
811 // constructor, one is declared implicitly.
812
813 // C++ [class.copy]p5:
814 // The implicitly-declared copy constructor for a class X will
815 // have the form
816 //
817 // X::X(const X&)
818 //
819 // if
820 bool HasConstCopyConstructor = true;
821
822 // -- each direct or virtual base class B of X has a copy
823 // constructor whose first parameter is of type const B& or
824 // const volatile B&, and
825 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
826 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
827 const CXXRecordDecl *BaseClassDecl
828 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
829 HasConstCopyConstructor
830 = BaseClassDecl->hasConstCopyConstructor(Context);
831 }
832
833 // -- for all the nonstatic data members of X that are of a
834 // class type M (or array thereof), each such class type
835 // has a copy constructor whose first parameter is of type
836 // const M& or const volatile M&.
837 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
838 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
839 QualType FieldType = (*Field)->getType();
840 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
841 FieldType = Array->getElementType();
842 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
843 const CXXRecordDecl *FieldClassDecl
844 = cast<CXXRecordDecl>(FieldClassType->getDecl());
845 HasConstCopyConstructor
846 = FieldClassDecl->hasConstCopyConstructor(Context);
847 }
848 }
849
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000850 // Otherwise, the implicitly declared copy constructor will have
851 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000852 //
853 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000854 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000855 if (HasConstCopyConstructor)
856 ArgType = ArgType.withConst();
857 ArgType = Context.getReferenceType(ArgType);
858
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000859 // An implicitly-declared copy constructor is an inline public
860 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000861 DeclarationName Name
862 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000863 CXXConstructorDecl *CopyConstructor
864 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000865 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000866 Context.getFunctionType(Context.VoidTy,
867 &ArgType, 1,
868 false, 0),
869 /*isExplicit=*/false,
870 /*isInline=*/true,
871 /*isImplicitlyDeclared=*/true);
872 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000873 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000874
875 // Add the parameter to the constructor.
876 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
877 ClassDecl->getLocation(),
878 /*IdentifierInfo=*/0,
879 ArgType, VarDecl::None, 0, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000880 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000881
Douglas Gregorb9213832008-12-15 21:24:18 +0000882 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000883 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000884 }
885
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000886 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
887 // Note: The following rules are largely analoguous to the copy
888 // constructor rules. Note that virtual bases are not taken into account
889 // for determining the argument type of the operator. Note also that
890 // operators taking an object instead of a reference are allowed.
891 //
892 // C++ [class.copy]p10:
893 // If the class definition does not explicitly declare a copy
894 // assignment operator, one is declared implicitly.
895 // The implicitly-defined copy assignment operator for a class X
896 // will have the form
897 //
898 // X& X::operator=(const X&)
899 //
900 // if
901 bool HasConstCopyAssignment = true;
902
903 // -- each direct base class B of X has a copy assignment operator
904 // whose parameter is of type const B&, const volatile B& or B,
905 // and
906 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
907 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
908 const CXXRecordDecl *BaseClassDecl
909 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
910 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
911 }
912
913 // -- for all the nonstatic data members of X that are of a class
914 // type M (or array thereof), each such class type has a copy
915 // assignment operator whose parameter is of type const M&,
916 // const volatile M& or M.
917 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
918 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
919 QualType FieldType = (*Field)->getType();
920 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
921 FieldType = Array->getElementType();
922 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
923 const CXXRecordDecl *FieldClassDecl
924 = cast<CXXRecordDecl>(FieldClassType->getDecl());
925 HasConstCopyAssignment
926 = FieldClassDecl->hasConstCopyAssignment(Context);
927 }
928 }
929
930 // Otherwise, the implicitly declared copy assignment operator will
931 // have the form
932 //
933 // X& X::operator=(X&)
934 QualType ArgType = ClassType;
935 QualType RetType = Context.getReferenceType(ArgType);
936 if (HasConstCopyAssignment)
937 ArgType = ArgType.withConst();
938 ArgType = Context.getReferenceType(ArgType);
939
940 // An implicitly-declared copy assignment operator is an inline public
941 // member of its class.
942 DeclarationName Name =
943 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
944 CXXMethodDecl *CopyAssignment =
945 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
946 Context.getFunctionType(RetType, &ArgType, 1,
947 false, 0),
948 /*isStatic=*/false, /*isInline=*/true, 0);
949 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000950 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000951
952 // Add the parameter to the operator.
953 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
954 ClassDecl->getLocation(),
955 /*IdentifierInfo=*/0,
956 ArgType, VarDecl::None, 0, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000957 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000958
959 // Don't call addedAssignmentOperator. There is no way to distinguish an
960 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000961 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000962 }
963
Douglas Gregorb9213832008-12-15 21:24:18 +0000964 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000965 // C++ [class.dtor]p2:
966 // If a class has no user-declared destructor, a destructor is
967 // declared implicitly. An implicitly-declared destructor is an
968 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000969 DeclarationName Name
970 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000971 CXXDestructorDecl *Destructor
972 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000973 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000974 Context.getFunctionType(Context.VoidTy,
975 0, 0, false, 0),
976 /*isInline=*/true,
977 /*isImplicitlyDeclared=*/true);
978 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000979 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000980 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000981 }
Douglas Gregore640ab62008-11-03 17:51:48 +0000982}
983
Douglas Gregor605de8d2008-12-16 21:30:33 +0000984/// ActOnStartDelayedCXXMethodDeclaration - We have completed
985/// parsing a top-level (non-nested) C++ class, and we are now
986/// parsing those parts of the given Method declaration that could
987/// not be parsed earlier (C++ [class.mem]p2), such as default
988/// arguments. This action should enter the scope of the given
989/// Method declaration as if we had just parsed the qualified method
990/// name. However, it should not bring the parameters into scope;
991/// that will be performed by ActOnDelayedCXXMethodParameter.
992void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
993 CXXScopeSpec SS;
994 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
995 ActOnCXXEnterDeclaratorScope(S, SS);
996}
997
998/// ActOnDelayedCXXMethodParameter - We've already started a delayed
999/// C++ method declaration. We're (re-)introducing the given
1000/// function parameter into scope for use in parsing later parts of
1001/// the method declaration. For example, we could see an
1002/// ActOnParamDefaultArgument event for this parameter.
1003void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1004 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001005
1006 // If this parameter has an unparsed default argument, clear it out
1007 // to make way for the parsed default argument.
1008 if (Param->hasUnparsedDefaultArg())
1009 Param->setDefaultArg(0);
1010
Douglas Gregor605de8d2008-12-16 21:30:33 +00001011 S->AddDecl(Param);
1012 if (Param->getDeclName())
1013 IdResolver.AddDecl(Param);
1014}
1015
1016/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1017/// processing the delayed method declaration for Method. The method
1018/// declaration is now considered finished. There may be a separate
1019/// ActOnStartOfFunctionDef action later (not necessarily
1020/// immediately!) for this method, if it was also defined inside the
1021/// class body.
1022void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1023 FunctionDecl *Method = (FunctionDecl*)MethodD;
1024 CXXScopeSpec SS;
1025 SS.setScopeRep(Method->getDeclContext());
1026 ActOnCXXExitDeclaratorScope(S, SS);
1027
1028 // Now that we have our default arguments, check the constructor
1029 // again. It could produce additional diagnostics or affect whether
1030 // the class has implicitly-declared destructors, among other
1031 // things.
1032 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1033 if (CheckConstructor(Constructor))
1034 Constructor->setInvalidDecl();
1035 }
1036
1037 // Check the default arguments, which we may have added.
1038 if (!Method->isInvalidDecl())
1039 CheckCXXDefaultArguments(Method);
1040}
1041
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001042/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001043/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001044/// R. If there are any errors in the declarator, this routine will
1045/// emit diagnostics and return true. Otherwise, it will return
1046/// false. Either way, the type @p R will be updated to reflect a
1047/// well-formed type for the constructor.
1048bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1049 FunctionDecl::StorageClass& SC) {
1050 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1051 bool isInvalid = false;
1052
1053 // C++ [class.ctor]p3:
1054 // A constructor shall not be virtual (10.3) or static (9.4). A
1055 // constructor can be invoked for a const, volatile or const
1056 // volatile object. A constructor shall not be declared const,
1057 // volatile, or const volatile (9.3.2).
1058 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001059 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1060 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1061 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001062 isInvalid = true;
1063 }
1064 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001065 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1066 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1067 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001068 isInvalid = true;
1069 SC = FunctionDecl::None;
1070 }
1071 if (D.getDeclSpec().hasTypeSpecifier()) {
1072 // Constructors don't have return types, but the parser will
1073 // happily parse something like:
1074 //
1075 // class X {
1076 // float X(float);
1077 // };
1078 //
1079 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001080 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1081 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1082 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001083 }
1084 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1085 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1086 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001087 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1088 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001089 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001090 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1091 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001092 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001093 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1094 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001095 }
1096
1097 // Rebuild the function type "R" without any type qualifiers (in
1098 // case any of the errors above fired) and with "void" as the
1099 // return type, since constructors don't have return types. We
1100 // *always* have to do this, because GetTypeForDeclarator will
1101 // put in a result type of "int" when none was specified.
1102 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1103 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1104 Proto->getNumArgs(),
1105 Proto->isVariadic(),
1106 0);
1107
1108 return isInvalid;
1109}
1110
Douglas Gregor605de8d2008-12-16 21:30:33 +00001111/// CheckConstructor - Checks a fully-formed constructor for
1112/// well-formedness, issuing any diagnostics required. Returns true if
1113/// the constructor declarator is invalid.
1114bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1115 if (Constructor->isInvalidDecl())
1116 return true;
1117
1118 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1119 bool Invalid = false;
1120
1121 // C++ [class.copy]p3:
1122 // A declaration of a constructor for a class X is ill-formed if
1123 // its first parameter is of type (optionally cv-qualified) X and
1124 // either there are no other parameters or else all other
1125 // parameters have default arguments.
1126 if ((Constructor->getNumParams() == 1) ||
1127 (Constructor->getNumParams() > 1 &&
1128 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1129 QualType ParamType = Constructor->getParamDecl(0)->getType();
1130 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1131 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1132 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1133 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1134 Invalid = true;
1135 }
1136 }
1137
1138 // Notify the class that we've added a constructor.
1139 ClassDecl->addedConstructor(Context, Constructor);
1140
1141 return Invalid;
1142}
1143
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001144/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1145/// the well-formednes of the destructor declarator @p D with type @p
1146/// R. If there are any errors in the declarator, this routine will
1147/// emit diagnostics and return true. Otherwise, it will return
1148/// false. Either way, the type @p R will be updated to reflect a
1149/// well-formed type for the destructor.
1150bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1151 FunctionDecl::StorageClass& SC) {
1152 bool isInvalid = false;
1153
1154 // C++ [class.dtor]p1:
1155 // [...] A typedef-name that names a class is a class-name
1156 // (7.1.3); however, a typedef-name that names a class shall not
1157 // be used as the identifier in the declarator for a destructor
1158 // declaration.
1159 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1160 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001161 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattner271d4c22008-11-24 05:29:24 +00001162 << TypedefD->getDeclName();
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001163 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001164 }
1165
1166 // C++ [class.dtor]p2:
1167 // A destructor is used to destroy objects of its class type. A
1168 // destructor takes no parameters, and no return type can be
1169 // specified for it (not even void). The address of a destructor
1170 // shall not be taken. A destructor shall not be static. A
1171 // destructor can be invoked for a const, volatile or const
1172 // volatile object. A destructor shall not be declared const,
1173 // volatile or const volatile (9.3.2).
1174 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001175 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1176 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1177 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001178 isInvalid = true;
1179 SC = FunctionDecl::None;
1180 }
1181 if (D.getDeclSpec().hasTypeSpecifier()) {
1182 // Destructors don't have return types, but the parser will
1183 // happily parse something like:
1184 //
1185 // class X {
1186 // float ~X();
1187 // };
1188 //
1189 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001190 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1191 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1192 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001193 }
1194 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1195 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1196 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001197 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1198 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001199 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001200 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1201 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001202 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001203 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1204 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001205 }
1206
1207 // Make sure we don't have any parameters.
1208 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1209 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1210
1211 // Delete the parameters.
1212 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1213 if (FTI.NumArgs) {
1214 delete [] FTI.ArgInfo;
1215 FTI.NumArgs = 0;
1216 FTI.ArgInfo = 0;
1217 }
1218 }
1219
1220 // Make sure the destructor isn't variadic.
1221 if (R->getAsFunctionTypeProto()->isVariadic())
1222 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1223
1224 // Rebuild the function type "R" without any type qualifiers or
1225 // parameters (in case any of the errors above fired) and with
1226 // "void" as the return type, since destructors don't have return
1227 // types. We *always* have to do this, because GetTypeForDeclarator
1228 // will put in a result type of "int" when none was specified.
1229 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1230
1231 return isInvalid;
1232}
1233
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001234/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1235/// well-formednes of the conversion function declarator @p D with
1236/// type @p R. If there are any errors in the declarator, this routine
1237/// will emit diagnostics and return true. Otherwise, it will return
1238/// false. Either way, the type @p R will be updated to reflect a
1239/// well-formed type for the conversion operator.
1240bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1241 FunctionDecl::StorageClass& SC) {
1242 bool isInvalid = false;
1243
1244 // C++ [class.conv.fct]p1:
1245 // Neither parameter types nor return type can be specified. The
1246 // type of a conversion function (8.3.5) is “function taking no
1247 // parameter returning conversion-type-id.”
1248 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001249 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1250 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1251 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001252 isInvalid = true;
1253 SC = FunctionDecl::None;
1254 }
1255 if (D.getDeclSpec().hasTypeSpecifier()) {
1256 // Conversion functions don't have return types, but the parser will
1257 // happily parse something like:
1258 //
1259 // class X {
1260 // float operator bool();
1261 // };
1262 //
1263 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001264 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1265 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1266 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001267 }
1268
1269 // Make sure we don't have any parameters.
1270 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1271 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1272
1273 // Delete the parameters.
1274 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1275 if (FTI.NumArgs) {
1276 delete [] FTI.ArgInfo;
1277 FTI.NumArgs = 0;
1278 FTI.ArgInfo = 0;
1279 }
1280 }
1281
1282 // Make sure the conversion function isn't variadic.
1283 if (R->getAsFunctionTypeProto()->isVariadic())
1284 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1285
1286 // C++ [class.conv.fct]p4:
1287 // The conversion-type-id shall not represent a function type nor
1288 // an array type.
1289 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1290 if (ConvType->isArrayType()) {
1291 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1292 ConvType = Context.getPointerType(ConvType);
1293 } else if (ConvType->isFunctionType()) {
1294 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1295 ConvType = Context.getPointerType(ConvType);
1296 }
1297
1298 // Rebuild the function type "R" without any parameters (in case any
1299 // of the errors above fired) and with the conversion type as the
1300 // return type.
1301 R = Context.getFunctionType(ConvType, 0, 0, false,
1302 R->getAsFunctionTypeProto()->getTypeQuals());
1303
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001304 // C++0x explicit conversion operators.
1305 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1306 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1307 diag::warn_explicit_conversion_functions)
1308 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1309
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001310 return isInvalid;
1311}
1312
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001313/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1314/// the declaration of the given C++ conversion function. This routine
1315/// is responsible for recording the conversion function in the C++
1316/// class, if possible.
1317Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1318 assert(Conversion && "Expected to receive a conversion function declaration");
1319
Douglas Gregor98341042008-12-12 08:25:50 +00001320 // Set the lexical context of this conversion function
1321 Conversion->setLexicalDeclContext(CurContext);
1322
1323 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001324
1325 // Make sure we aren't redeclaring the conversion function.
1326 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001327
1328 // C++ [class.conv.fct]p1:
1329 // [...] A conversion function is never used to convert a
1330 // (possibly cv-qualified) object to the (possibly cv-qualified)
1331 // same object type (or a reference to it), to a (possibly
1332 // cv-qualified) base class of that type (or a reference to it),
1333 // or to (possibly cv-qualified) void.
1334 // FIXME: Suppress this warning if the conversion function ends up
1335 // being a virtual function that overrides a virtual function in a
1336 // base class.
1337 QualType ClassType
1338 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1339 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1340 ConvType = ConvTypeRef->getPointeeType();
1341 if (ConvType->isRecordType()) {
1342 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1343 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001344 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001345 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001346 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001347 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001348 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001349 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001350 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001351 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001352 }
1353
Douglas Gregor853dd392008-12-26 15:00:45 +00001354 if (Conversion->getPreviousDeclaration()) {
1355 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1356 for (OverloadedFunctionDecl::function_iterator
1357 Conv = Conversions->function_begin(),
1358 ConvEnd = Conversions->function_end();
1359 Conv != ConvEnd; ++Conv) {
1360 if (*Conv == Conversion->getPreviousDeclaration()) {
1361 *Conv = Conversion;
1362 return (DeclTy *)Conversion;
1363 }
1364 }
1365 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1366 } else
1367 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001368
1369 return (DeclTy *)Conversion;
1370}
1371
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001372//===----------------------------------------------------------------------===//
1373// Namespace Handling
1374//===----------------------------------------------------------------------===//
1375
1376/// ActOnStartNamespaceDef - This is called at the start of a namespace
1377/// definition.
1378Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1379 SourceLocation IdentLoc,
1380 IdentifierInfo *II,
1381 SourceLocation LBrace) {
1382 NamespaceDecl *Namespc =
1383 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1384 Namespc->setLBracLoc(LBrace);
1385
1386 Scope *DeclRegionScope = NamespcScope->getParent();
1387
1388 if (II) {
1389 // C++ [namespace.def]p2:
1390 // The identifier in an original-namespace-definition shall not have been
1391 // previously defined in the declarative region in which the
1392 // original-namespace-definition appears. The identifier in an
1393 // original-namespace-definition is the name of the namespace. Subsequently
1394 // in that declarative region, it is treated as an original-namespace-name.
1395
1396 Decl *PrevDecl =
Douglas Gregor78d70132009-01-14 22:20:51 +00001397 LookupDecl(II, Decl::IDNS_Ordinary, DeclRegionScope, 0,
Douglas Gregor8acb7272008-12-11 16:49:14 +00001398 /*enableLazyBuiltinCreation=*/false,
1399 /*LookupInParent=*/false);
1400
1401 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1402 // This is an extended namespace definition.
1403 // Attach this namespace decl to the chain of extended namespace
1404 // definitions.
1405 OrigNS->setNextNamespace(Namespc);
1406 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001407
Douglas Gregor8acb7272008-12-11 16:49:14 +00001408 // Remove the previous declaration from the scope.
1409 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001410 IdResolver.RemoveDecl(OrigNS);
1411 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001412 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001413 } else if (PrevDecl) {
1414 // This is an invalid name redefinition.
1415 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1416 << Namespc->getDeclName();
1417 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1418 Namespc->setInvalidDecl();
1419 // Continue on to push Namespc as current DeclContext and return it.
1420 }
1421
1422 PushOnScopeChains(Namespc, DeclRegionScope);
1423 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001424 // FIXME: Handle anonymous namespaces
1425 }
1426
1427 // Although we could have an invalid decl (i.e. the namespace name is a
1428 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001429 // FIXME: We should be able to push Namespc here, so that the
1430 // each DeclContext for the namespace has the declarations
1431 // that showed up in that particular namespace definition.
1432 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001433 return Namespc;
1434}
1435
1436/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1437/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1438void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1439 Decl *Dcl = static_cast<Decl *>(D);
1440 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1441 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1442 Namespc->setRBracLoc(RBrace);
1443 PopDeclContext();
1444}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001445
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001446Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1447 SourceLocation UsingLoc,
1448 SourceLocation NamespcLoc,
1449 const CXXScopeSpec &SS,
1450 SourceLocation IdentLoc,
1451 IdentifierInfo *NamespcName,
1452 AttributeList *AttrList) {
1453 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1454 assert(NamespcName && "Invalid NamespcName.");
1455 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1456
1457 // FIXME: This still requires lot more checks, and AST support.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001458
Douglas Gregor78d70132009-01-14 22:20:51 +00001459 // Lookup namespace name.
1460 LookupCriteria Criteria(LookupCriteria::Namespace, /*RedeclarationOnly=*/false,
1461 /*CPlusPlus=*/true);
1462 Decl *NS = 0;
1463 if (SS.isSet())
1464 NS = LookupQualifiedName(static_cast<DeclContext*>(SS.getScopeRep()),
1465 NamespcName, Criteria);
1466 else
1467 NS = LookupName(S, NamespcName, Criteria);
1468
1469 if (NS) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001470 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1471 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001472 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001473 }
1474
1475 // FIXME: We ignore AttrList for now, and delete it to avoid leak.
1476 delete AttrList;
1477 return 0;
1478}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001479
1480/// AddCXXDirectInitializerToDecl - This action is called immediately after
1481/// ActOnDeclarator, when a C++ direct initializer is present.
1482/// e.g: "int x(1);"
1483void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1484 ExprTy **ExprTys, unsigned NumExprs,
1485 SourceLocation *CommaLocs,
1486 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001487 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001488 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001489
1490 // If there is no declaration, there was an error parsing it. Just ignore
1491 // the initializer.
1492 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001493 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001494 delete static_cast<Expr *>(ExprTys[i]);
1495 return;
1496 }
1497
1498 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1499 if (!VDecl) {
1500 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1501 RealDecl->setInvalidDecl();
1502 return;
1503 }
1504
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001505 // We will treat direct-initialization as a copy-initialization:
1506 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001507 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1508 //
1509 // Clients that want to distinguish between the two forms, can check for
1510 // direct initializer using VarDecl::hasCXXDirectInitializer().
1511 // A major benefit is that clients that don't particularly care about which
1512 // exactly form was it (like the CodeGen) can handle both cases without
1513 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001514
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001515 // C++ 8.5p11:
1516 // The form of initialization (using parentheses or '=') is generally
1517 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001518 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001519 QualType DeclInitType = VDecl->getType();
1520 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1521 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001522
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001523 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001524 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001525 = PerformInitializationByConstructor(DeclInitType,
1526 (Expr **)ExprTys, NumExprs,
1527 VDecl->getLocation(),
1528 SourceRange(VDecl->getLocation(),
1529 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001530 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001531 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001532 if (!Constructor) {
1533 RealDecl->setInvalidDecl();
1534 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001535
1536 // Let clients know that initialization was done with a direct
1537 // initializer.
1538 VDecl->setCXXDirectInitializer(true);
1539
1540 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1541 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001542 return;
1543 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001544
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001545 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001546 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1547 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001548 RealDecl->setInvalidDecl();
1549 return;
1550 }
1551
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001552 // Let clients know that initialization was done with a direct initializer.
1553 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001554
1555 assert(NumExprs == 1 && "Expected 1 expression");
1556 // Set the init expression, handles conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001557 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001558}
Douglas Gregor81c29152008-10-29 00:13:59 +00001559
Douglas Gregor6428e762008-11-05 15:29:30 +00001560/// PerformInitializationByConstructor - Perform initialization by
1561/// constructor (C++ [dcl.init]p14), which may occur as part of
1562/// direct-initialization or copy-initialization. We are initializing
1563/// an object of type @p ClassType with the given arguments @p
1564/// Args. @p Loc is the location in the source code where the
1565/// initializer occurs (e.g., a declaration, member initializer,
1566/// functional cast, etc.) while @p Range covers the whole
1567/// initialization. @p InitEntity is the entity being initialized,
1568/// which may by the name of a declaration or a type. @p Kind is the
1569/// kind of initialization we're performing, which affects whether
1570/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001571/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001572/// when the initialization fails, emits a diagnostic and returns
1573/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001574CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001575Sema::PerformInitializationByConstructor(QualType ClassType,
1576 Expr **Args, unsigned NumArgs,
1577 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001578 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001579 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001580 const RecordType *ClassRec = ClassType->getAsRecordType();
1581 assert(ClassRec && "Can only initialize a class type here");
1582
1583 // C++ [dcl.init]p14:
1584 //
1585 // If the initialization is direct-initialization, or if it is
1586 // copy-initialization where the cv-unqualified version of the
1587 // source type is the same class as, or a derived class of, the
1588 // class of the destination, constructors are considered. The
1589 // applicable constructors are enumerated (13.3.1.3), and the
1590 // best one is chosen through overload resolution (13.3). The
1591 // constructor so selected is called to initialize the object,
1592 // with the initializer expression(s) as its argument(s). If no
1593 // constructor applies, or the overload resolution is ambiguous,
1594 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001595 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1596 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001597
1598 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001599 DeclarationName ConstructorName
1600 = Context.DeclarationNames.getCXXConstructorName(
1601 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001602 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001603 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001604 Con != ConEnd; ++Con) {
1605 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001606 if ((Kind == IK_Direct) ||
1607 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1608 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1609 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1610 }
1611
Douglas Gregorb9213832008-12-15 21:24:18 +00001612 // FIXME: When we decide not to synthesize the implicitly-declared
1613 // constructors, we'll need to make them appear here.
1614
Douglas Gregor5870a952008-11-03 20:45:27 +00001615 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001616 switch (BestViableFunction(CandidateSet, Best)) {
1617 case OR_Success:
1618 // We found a constructor. Return it.
1619 return cast<CXXConstructorDecl>(Best->Function);
1620
1621 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001622 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1623 << InitEntity << (unsigned)CandidateSet.size() << Range;
1624 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001625 return 0;
1626
1627 case OR_Ambiguous:
Chris Lattner77d52da2008-11-20 06:06:08 +00001628 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001629 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1630 return 0;
1631 }
1632
1633 return 0;
1634}
1635
Douglas Gregor81c29152008-10-29 00:13:59 +00001636/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1637/// determine whether they are reference-related,
1638/// reference-compatible, reference-compatible with added
1639/// qualification, or incompatible, for use in C++ initialization by
1640/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1641/// type, and the first type (T1) is the pointee type of the reference
1642/// type being initialized.
1643Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001644Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1645 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001646 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1647 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1648
1649 T1 = Context.getCanonicalType(T1);
1650 T2 = Context.getCanonicalType(T2);
1651 QualType UnqualT1 = T1.getUnqualifiedType();
1652 QualType UnqualT2 = T2.getUnqualifiedType();
1653
1654 // C++ [dcl.init.ref]p4:
1655 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1656 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1657 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001658 if (UnqualT1 == UnqualT2)
1659 DerivedToBase = false;
1660 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1661 DerivedToBase = true;
1662 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001663 return Ref_Incompatible;
1664
1665 // At this point, we know that T1 and T2 are reference-related (at
1666 // least).
1667
1668 // C++ [dcl.init.ref]p4:
1669 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1670 // reference-related to T2 and cv1 is the same cv-qualification
1671 // as, or greater cv-qualification than, cv2. For purposes of
1672 // overload resolution, cases for which cv1 is greater
1673 // cv-qualification than cv2 are identified as
1674 // reference-compatible with added qualification (see 13.3.3.2).
1675 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1676 return Ref_Compatible;
1677 else if (T1.isMoreQualifiedThan(T2))
1678 return Ref_Compatible_With_Added_Qualification;
1679 else
1680 return Ref_Related;
1681}
1682
1683/// CheckReferenceInit - Check the initialization of a reference
1684/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1685/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001686/// list), and DeclType is the type of the declaration. When ICS is
1687/// non-null, this routine will compute the implicit conversion
1688/// sequence according to C++ [over.ics.ref] and will not produce any
1689/// diagnostics; when ICS is null, it will emit diagnostics when any
1690/// errors are found. Either way, a return value of true indicates
1691/// that there was a failure, a return value of false indicates that
1692/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001693///
1694/// When @p SuppressUserConversions, user-defined conversions are
1695/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001696/// When @p AllowExplicit, we also permit explicit user-defined
1697/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001698bool
1699Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001700 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001701 bool SuppressUserConversions,
1702 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001703 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1704
1705 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1706 QualType T2 = Init->getType();
1707
Douglas Gregor45014fd2008-11-10 20:40:00 +00001708 // If the initializer is the address of an overloaded function, try
1709 // to resolve the overloaded function. If all goes well, T2 is the
1710 // type of the resulting function.
1711 if (T2->isOverloadType()) {
1712 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1713 ICS != 0);
1714 if (Fn) {
1715 // Since we're performing this reference-initialization for
1716 // real, update the initializer with the resulting function.
1717 if (!ICS)
1718 FixOverloadedFunctionReference(Init, Fn);
1719
1720 T2 = Fn->getType();
1721 }
1722 }
1723
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001724 // Compute some basic properties of the types and the initializer.
1725 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001726 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001727 ReferenceCompareResult RefRelationship
1728 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1729
1730 // Most paths end in a failed conversion.
1731 if (ICS)
1732 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001733
1734 // C++ [dcl.init.ref]p5:
1735 // A reference to type “cv1 T1” is initialized by an expression
1736 // of type “cv2 T2” as follows:
1737
1738 // -- If the initializer expression
1739
1740 bool BindsDirectly = false;
1741 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1742 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001743 //
1744 // Note that the bit-field check is skipped if we are just computing
1745 // the implicit conversion sequence (C++ [over.best.ics]p2).
1746 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1747 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001748 BindsDirectly = true;
1749
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001750 if (ICS) {
1751 // C++ [over.ics.ref]p1:
1752 // When a parameter of reference type binds directly (8.5.3)
1753 // to an argument expression, the implicit conversion sequence
1754 // is the identity conversion, unless the argument expression
1755 // has a type that is a derived class of the parameter type,
1756 // in which case the implicit conversion sequence is a
1757 // derived-to-base Conversion (13.3.3.1).
1758 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1759 ICS->Standard.First = ICK_Identity;
1760 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1761 ICS->Standard.Third = ICK_Identity;
1762 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1763 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001764 ICS->Standard.ReferenceBinding = true;
1765 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001766
1767 // Nothing more to do: the inaccessibility/ambiguity check for
1768 // derived-to-base conversions is suppressed when we're
1769 // computing the implicit conversion sequence (C++
1770 // [over.best.ics]p2).
1771 return false;
1772 } else {
1773 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001774 // FIXME: Binding to a subobject of the lvalue is going to require
1775 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001776 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001777 }
1778 }
1779
1780 // -- has a class type (i.e., T2 is a class type) and can be
1781 // implicitly converted to an lvalue of type “cv3 T3,”
1782 // where “cv1 T1” is reference-compatible with “cv3 T3”
1783 // 92) (this conversion is selected by enumerating the
1784 // applicable conversion functions (13.3.1.6) and choosing
1785 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001786 if (!SuppressUserConversions && T2->isRecordType()) {
1787 // FIXME: Look for conversions in base classes!
1788 CXXRecordDecl *T2RecordDecl
1789 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001790
Douglas Gregore6985fe2008-11-10 16:14:15 +00001791 OverloadCandidateSet CandidateSet;
1792 OverloadedFunctionDecl *Conversions
1793 = T2RecordDecl->getConversionFunctions();
1794 for (OverloadedFunctionDecl::function_iterator Func
1795 = Conversions->function_begin();
1796 Func != Conversions->function_end(); ++Func) {
1797 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1798
1799 // If the conversion function doesn't return a reference type,
1800 // it can't be considered for this conversion.
1801 // FIXME: This will change when we support rvalue references.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001802 if (Conv->getConversionType()->isReferenceType() &&
1803 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001804 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1805 }
1806
1807 OverloadCandidateSet::iterator Best;
1808 switch (BestViableFunction(CandidateSet, Best)) {
1809 case OR_Success:
1810 // This is a direct binding.
1811 BindsDirectly = true;
1812
1813 if (ICS) {
1814 // C++ [over.ics.ref]p1:
1815 //
1816 // [...] If the parameter binds directly to the result of
1817 // applying a conversion function to the argument
1818 // expression, the implicit conversion sequence is a
1819 // user-defined conversion sequence (13.3.3.1.2), with the
1820 // second standard conversion sequence either an identity
1821 // conversion or, if the conversion function returns an
1822 // entity of a type that is a derived class of the parameter
1823 // type, a derived-to-base Conversion.
1824 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1825 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1826 ICS->UserDefined.After = Best->FinalConversion;
1827 ICS->UserDefined.ConversionFunction = Best->Function;
1828 assert(ICS->UserDefined.After.ReferenceBinding &&
1829 ICS->UserDefined.After.DirectBinding &&
1830 "Expected a direct reference binding!");
1831 return false;
1832 } else {
1833 // Perform the conversion.
1834 // FIXME: Binding to a subobject of the lvalue is going to require
1835 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001836 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001837 }
1838 break;
1839
1840 case OR_Ambiguous:
1841 assert(false && "Ambiguous reference binding conversions not implemented.");
1842 return true;
1843
1844 case OR_No_Viable_Function:
1845 // There was no suitable conversion; continue with other checks.
1846 break;
1847 }
1848 }
1849
Douglas Gregor81c29152008-10-29 00:13:59 +00001850 if (BindsDirectly) {
1851 // C++ [dcl.init.ref]p4:
1852 // [...] In all cases where the reference-related or
1853 // reference-compatible relationship of two types is used to
1854 // establish the validity of a reference binding, and T1 is a
1855 // base class of T2, a program that necessitates such a binding
1856 // is ill-formed if T1 is an inaccessible (clause 11) or
1857 // ambiguous (10.2) base class of T2.
1858 //
1859 // Note that we only check this condition when we're allowed to
1860 // complain about errors, because we should not be checking for
1861 // ambiguity (or inaccessibility) unless the reference binding
1862 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001863 if (DerivedToBase)
1864 return CheckDerivedToBaseConversion(T2, T1,
1865 Init->getSourceRange().getBegin(),
1866 Init->getSourceRange());
1867 else
1868 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001869 }
1870
1871 // -- Otherwise, the reference shall be to a non-volatile const
1872 // type (i.e., cv1 shall be const).
1873 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001874 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001875 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001876 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001877 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1878 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001879 return true;
1880 }
1881
1882 // -- If the initializer expression is an rvalue, with T2 a
1883 // class type, and “cv1 T1” is reference-compatible with
1884 // “cv2 T2,” the reference is bound in one of the
1885 // following ways (the choice is implementation-defined):
1886 //
1887 // -- The reference is bound to the object represented by
1888 // the rvalue (see 3.10) or to a sub-object within that
1889 // object.
1890 //
1891 // -- A temporary of type “cv1 T2” [sic] is created, and
1892 // a constructor is called to copy the entire rvalue
1893 // object into the temporary. The reference is bound to
1894 // the temporary or to a sub-object within the
1895 // temporary.
1896 //
1897 //
1898 // The constructor that would be used to make the copy
1899 // shall be callable whether or not the copy is actually
1900 // done.
1901 //
1902 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1903 // freedom, so we will always take the first option and never build
1904 // a temporary in this case. FIXME: We will, however, have to check
1905 // for the presence of a copy constructor in C++98/03 mode.
1906 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001907 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1908 if (ICS) {
1909 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1910 ICS->Standard.First = ICK_Identity;
1911 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1912 ICS->Standard.Third = ICK_Identity;
1913 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1914 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001915 ICS->Standard.ReferenceBinding = true;
1916 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001917 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001918 // FIXME: Binding to a subobject of the rvalue is going to require
1919 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001920 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001921 }
1922 return false;
1923 }
1924
1925 // -- Otherwise, a temporary of type “cv1 T1” is created and
1926 // initialized from the initializer expression using the
1927 // rules for a non-reference copy initialization (8.5). The
1928 // reference is then bound to the temporary. If T1 is
1929 // reference-related to T2, cv1 must be the same
1930 // cv-qualification as, or greater cv-qualification than,
1931 // cv2; otherwise, the program is ill-formed.
1932 if (RefRelationship == Ref_Related) {
1933 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1934 // we would be reference-compatible or reference-compatible with
1935 // added qualification. But that wasn't the case, so the reference
1936 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001937 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001938 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001939 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001940 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1941 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001942 return true;
1943 }
1944
1945 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001946 if (ICS) {
1947 /// C++ [over.ics.ref]p2:
1948 ///
1949 /// When a parameter of reference type is not bound directly to
1950 /// an argument expression, the conversion sequence is the one
1951 /// required to convert the argument expression to the
1952 /// underlying type of the reference according to
1953 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1954 /// to copy-initializing a temporary of the underlying type with
1955 /// the argument expression. Any difference in top-level
1956 /// cv-qualification is subsumed by the initialization itself
1957 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001958 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001959 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1960 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00001961 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001962 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001963}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001964
1965/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1966/// of this overloaded operator is well-formed. If so, returns false;
1967/// otherwise, emits appropriate diagnostics and returns true.
1968bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001969 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00001970 "Expected an overloaded operator declaration");
1971
Douglas Gregore60e5d32008-11-06 22:13:31 +00001972 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1973
1974 // C++ [over.oper]p5:
1975 // The allocation and deallocation functions, operator new,
1976 // operator new[], operator delete and operator delete[], are
1977 // described completely in 3.7.3. The attributes and restrictions
1978 // found in the rest of this subclause do not apply to them unless
1979 // explicitly stated in 3.7.3.
1980 // FIXME: Write a separate routine for checking this. For now, just
1981 // allow it.
1982 if (Op == OO_New || Op == OO_Array_New ||
1983 Op == OO_Delete || Op == OO_Array_Delete)
1984 return false;
1985
1986 // C++ [over.oper]p6:
1987 // An operator function shall either be a non-static member
1988 // function or be a non-member function and have at least one
1989 // parameter whose type is a class, a reference to a class, an
1990 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001991 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1992 if (MethodDecl->isStatic())
1993 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001994 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001995 } else {
1996 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001997 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1998 ParamEnd = FnDecl->param_end();
1999 Param != ParamEnd; ++Param) {
2000 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002001 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2002 ClassOrEnumParam = true;
2003 break;
2004 }
2005 }
2006
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002007 if (!ClassOrEnumParam)
2008 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002009 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002010 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002011 }
2012
2013 // C++ [over.oper]p8:
2014 // An operator function cannot have default arguments (8.3.6),
2015 // except where explicitly stated below.
2016 //
2017 // Only the function-call operator allows default arguments
2018 // (C++ [over.call]p1).
2019 if (Op != OO_Call) {
2020 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2021 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002022 if ((*Param)->hasUnparsedDefaultArg())
2023 return Diag((*Param)->getLocation(),
2024 diag::err_operator_overload_default_arg)
2025 << FnDecl->getDeclName();
2026 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002027 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002028 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002029 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002030 }
2031 }
2032
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002033 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2034 { false, false, false }
2035#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2036 , { Unary, Binary, MemberOnly }
2037#include "clang/Basic/OperatorKinds.def"
2038 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002039
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002040 bool CanBeUnaryOperator = OperatorUses[Op][0];
2041 bool CanBeBinaryOperator = OperatorUses[Op][1];
2042 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002043
2044 // C++ [over.oper]p8:
2045 // [...] Operator functions cannot have more or fewer parameters
2046 // than the number required for the corresponding operator, as
2047 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002048 unsigned NumParams = FnDecl->getNumParams()
2049 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002050 if (Op != OO_Call &&
2051 ((NumParams == 1 && !CanBeUnaryOperator) ||
2052 (NumParams == 2 && !CanBeBinaryOperator) ||
2053 (NumParams < 1) || (NumParams > 2))) {
2054 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002055 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002056 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002057 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002058 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002059 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002060 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002061 assert(CanBeBinaryOperator &&
2062 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002063 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002064 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002065
Chris Lattnerbb002332008-11-21 07:57:12 +00002066 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002067 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002068 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002069
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002070 // Overloaded operators other than operator() cannot be variadic.
2071 if (Op != OO_Call &&
2072 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002073 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002074 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002075 }
2076
2077 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002078 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2079 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002080 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002081 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002082 }
2083
2084 // C++ [over.inc]p1:
2085 // The user-defined function called operator++ implements the
2086 // prefix and postfix ++ operator. If this function is a member
2087 // function with no parameters, or a non-member function with one
2088 // parameter of class or enumeration type, it defines the prefix
2089 // increment operator ++ for objects of that type. If the function
2090 // is a member function with one parameter (which shall be of type
2091 // int) or a non-member function with two parameters (the second
2092 // of which shall be of type int), it defines the postfix
2093 // increment operator ++ for objects of that type.
2094 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2095 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2096 bool ParamIsInt = false;
2097 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2098 ParamIsInt = BT->getKind() == BuiltinType::Int;
2099
Chris Lattnera7021ee2008-11-21 07:50:02 +00002100 if (!ParamIsInt)
2101 return Diag(LastParam->getLocation(),
2102 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002103 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002104 }
2105
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002106 // Notify the class if it got an assignment operator.
2107 if (Op == OO_Equal) {
2108 // Would have returned earlier otherwise.
2109 assert(isa<CXXMethodDecl>(FnDecl) &&
2110 "Overloaded = not member, but not filtered.");
2111 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2112 Method->getParent()->addedAssignmentOperator(Context, Method);
2113 }
2114
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002115 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002116}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002117
Douglas Gregord8028382009-01-05 19:45:36 +00002118/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2119/// linkage specification, including the language and (if present)
2120/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2121/// the location of the language string literal, which is provided
2122/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2123/// the '{' brace. Otherwise, this linkage specification does not
2124/// have any braces.
2125Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2126 SourceLocation ExternLoc,
2127 SourceLocation LangLoc,
2128 const char *Lang,
2129 unsigned StrSize,
2130 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002131 LinkageSpecDecl::LanguageIDs Language;
2132 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2133 Language = LinkageSpecDecl::lang_c;
2134 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2135 Language = LinkageSpecDecl::lang_cxx;
2136 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002137 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002138 return 0;
2139 }
2140
2141 // FIXME: Add all the various semantics of linkage specifications
2142
Douglas Gregord8028382009-01-05 19:45:36 +00002143 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2144 LangLoc, Language,
2145 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002146 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002147 PushDeclContext(S, D);
2148 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002149}
2150
Douglas Gregord8028382009-01-05 19:45:36 +00002151/// ActOnFinishLinkageSpecification - Completely the definition of
2152/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2153/// valid, it's the position of the closing '}' brace in a linkage
2154/// specification that uses braces.
2155Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2156 DeclTy *LinkageSpec,
2157 SourceLocation RBraceLoc) {
2158 if (LinkageSpec)
2159 PopDeclContext();
2160 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002161}
2162
Sebastian Redl743c8162008-12-22 19:15:10 +00002163/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2164/// handler.
2165Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2166{
2167 QualType ExDeclType = GetTypeForDeclarator(D, S);
2168 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2169
2170 bool Invalid = false;
2171
2172 // Arrays and functions decay.
2173 if (ExDeclType->isArrayType())
2174 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2175 else if (ExDeclType->isFunctionType())
2176 ExDeclType = Context.getPointerType(ExDeclType);
2177
2178 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2179 // The exception-declaration shall not denote a pointer or reference to an
2180 // incomplete type, other than [cv] void*.
2181 QualType BaseType = ExDeclType;
2182 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002183 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002184 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2185 BaseType = Ptr->getPointeeType();
2186 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002187 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002188 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2189 BaseType = Ref->getPointeeType();
2190 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002191 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002192 }
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002193 if ((Mode == 0 || !BaseType->isVoidType()) &&
2194 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002195 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002196
Sebastian Redl237116b2008-12-22 21:35:02 +00002197 // FIXME: Need to test for ability to copy-construct and destroy the
2198 // exception variable.
2199 // FIXME: Need to check for abstract classes.
2200
Sebastian Redl743c8162008-12-22 19:15:10 +00002201 IdentifierInfo *II = D.getIdentifier();
2202 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2203 // The scope should be freshly made just for us. There is just no way
2204 // it contains any previous declaration.
2205 assert(!S->isDeclScope(PrevDecl));
2206 if (PrevDecl->isTemplateParameter()) {
2207 // Maybe we will complain about the shadowed template parameter.
2208 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2209
2210 }
2211 }
2212
2213 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2214 II, ExDeclType, VarDecl::None, 0, Begin);
2215 if (D.getInvalidType() || Invalid)
2216 ExDecl->setInvalidDecl();
2217
2218 if (D.getCXXScopeSpec().isSet()) {
2219 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2220 << D.getCXXScopeSpec().getRange();
2221 ExDecl->setInvalidDecl();
2222 }
2223
2224 // Add the exception declaration into this scope.
2225 S->AddDecl(ExDecl);
2226 if (II)
2227 IdResolver.AddDecl(ExDecl);
2228
2229 ProcessDeclAttributes(ExDecl, D);
2230 return ExDecl;
2231}