blob: e67b8c0389706a4cece54a804ac0a9e0b4b2b25f [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000026#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner8123a952008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattner9e979552008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000044
Chris Lattner9e979552008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000052 };
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000061 }
62
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000088 }
Chris Lattner8123a952008-04-10 02:22:51 +000089
Douglas Gregor3996f232008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattner9e979552008-04-12 23:52:44 +000092
Douglas Gregor796da182008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102}
103
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000107void
108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
109 ExprTy *defarg) {
110 ParmVarDecl *Param = (ParmVarDecl *)param;
111 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
112 QualType ParamType = Param->getType();
113
114 // Default arguments are only permitted in C++
115 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 Diag(EqualLoc, diag::err_param_default_argument)
117 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000118 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000119 return;
120 }
121
122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Chris Lattner3d1cee32008-04-08 05:04:30 +0000128 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor61366e92008-12-24 00:01:03 +0000129 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
130 EqualLoc,
131 Param->getDeclName());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000144 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146
Chris Lattner3d1cee32008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor61366e92008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor72b505b2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor61366e92008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattner3d1cee32008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
204// type. Subroutine of MergeFunctionDecl.
205FunctionDecl *
206Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 // C++ [dcl.fct.default]p4:
208 //
209 // For non-template functions, default arguments can be added in
210 // later declarations of a function in the same
211 // scope. Declarations in different scopes have completely
212 // distinct sets of default arguments. That is, declarations in
213 // inner scopes do not acquire default arguments from
214 // declarations in outer scopes, and vice versa. In a given
215 // function declaration, all parameters subsequent to a
216 // parameter with a default argument shall have default
217 // arguments supplied in this or previous declarations. A
218 // default argument shall not be redefined by a later
219 // declaration (not even to the same value).
220 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
221 ParmVarDecl *OldParam = Old->getParamDecl(p);
222 ParmVarDecl *NewParam = New->getParamDecl(p);
223
224 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
225 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000226 diag::err_param_default_argument_redefinition)
227 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000228 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000229 } else if (OldParam->getDefaultArg()) {
230 // Merge the old default argument into the new parameter
231 NewParam->setDefaultArg(OldParam->getDefaultArg());
232 }
233 }
234
235 return New;
236}
237
238/// CheckCXXDefaultArguments - Verify that the default arguments for a
239/// function declaration are well-formed according to C++
240/// [dcl.fct.default].
241void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
242 unsigned NumParams = FD->getNumParams();
243 unsigned p;
244
245 // Find first parameter with a default argument
246 for (p = 0; p < NumParams; ++p) {
247 ParmVarDecl *Param = FD->getParamDecl(p);
248 if (Param->getDefaultArg())
249 break;
250 }
251
252 // C++ [dcl.fct.default]p4:
253 // In a given function declaration, all parameters
254 // subsequent to a parameter with a default argument shall
255 // have default arguments supplied in this or previous
256 // declarations. A default argument shall not be redefined
257 // by a later declaration (not even to the same value).
258 unsigned LastMissingDefaultArg = 0;
259 for(; p < NumParams; ++p) {
260 ParmVarDecl *Param = FD->getParamDecl(p);
261 if (!Param->getDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000262 if (Param->isInvalidDecl())
263 /* We already complained about this parameter. */;
264 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000265 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000266 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000267 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 else
269 Diag(Param->getLocation(),
270 diag::err_param_default_argument_missing);
271
272 LastMissingDefaultArg = p;
273 }
274 }
275
276 if (LastMissingDefaultArg > 0) {
277 // Some default arguments were missing. Clear out all of the
278 // default arguments up to (and including) the last missing
279 // default argument, so that we leave the function parameters
280 // in a semantically valid state.
281 for (p = 0; p <= LastMissingDefaultArg; ++p) {
282 ParmVarDecl *Param = FD->getParamDecl(p);
283 if (Param->getDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000284 if (!Param->hasUnparsedDefaultArg())
285 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000286 Param->setDefaultArg(0);
287 }
288 }
289 }
290}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000291
Douglas Gregorb48fe382008-10-31 09:07:45 +0000292/// isCurrentClassName - Determine whether the identifier II is the
293/// name of the class type currently being defined. In the case of
294/// nested classes, this will only return true if II is the name of
295/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000296bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
297 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000298 CXXRecordDecl *CurDecl;
299 if (SS) {
300 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
301 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
302 } else
303 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
304
305 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000306 return &II == CurDecl->getIdentifier();
307 else
308 return false;
309}
310
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000311/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
312/// one entry in the base class list of a class specifier, for
313/// example:
314/// class foo : public bar, virtual private baz {
315/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000316Sema::BaseResult
317Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
318 bool Virtual, AccessSpecifier Access,
319 TypeTy *basetype, SourceLocation BaseLoc) {
Sebastian Redl64b45f72009-01-05 20:52:13 +0000320 CXXRecordDecl *Decl = (CXXRecordDecl*)classdecl;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000321 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
322
323 // Base specifiers must be record types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000324 if (!BaseType->isRecordType())
325 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000326
327 // C++ [class.union]p1:
328 // A union shall not be used as a base class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000329 if (BaseType->isUnionType())
330 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000331
332 // C++ [class.union]p1:
333 // A union shall not have base classes.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000334 if (Decl->isUnion())
335 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
336 << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000337
338 // C++ [class.derived]p2:
339 // The class-name in a base-specifier shall not be an incompletely
340 // defined class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000341 if (BaseType->isIncompleteType())
342 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000343
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000344 // If the base class is polymorphic, the new one is, too.
345 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
346 assert(BaseDecl && "Record type has no declaration");
347 BaseDecl = BaseDecl->getDefinition(Context);
348 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000349 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl64b45f72009-01-05 20:52:13 +0000350 Decl->setPolymorphic(true);
351
352 // C++ [dcl.init.aggr]p1:
353 // An aggregate is [...] a class with [...] no base classes [...].
354 Decl->setAggregate(false);
355 Decl->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000356
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000357 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000358 return new CXXBaseSpecifier(SpecifierRange, Virtual,
359 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000360}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000361
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000362/// ActOnBaseSpecifiers - Attach the given base specifiers to the
363/// class, after checking whether there are any duplicate base
364/// classes.
365void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
366 unsigned NumBases) {
367 if (NumBases == 0)
368 return;
369
370 // Used to keep track of which base types we have already seen, so
371 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000372 // that the key is always the unqualified canonical type of the base
373 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000374 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
375
376 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000377 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
378 unsigned NumGoodBases = 0;
379 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000380 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000381 = Context.getCanonicalType(BaseSpecs[idx]->getType());
382 NewBaseType = NewBaseType.getUnqualifiedType();
383
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000384 if (KnownBaseTypes[NewBaseType]) {
385 // C++ [class.mi]p3:
386 // A class shall not be specified as a direct base class of a
387 // derived class more than once.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000388 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000390 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000391 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000392
393 // Delete the duplicate base class specifier; we're going to
394 // overwrite its pointer later.
395 delete BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000396 } else {
397 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000398 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
399 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000400 }
401 }
402
403 // Attach the remaining base class specifiers to the derived class.
404 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000405 Decl->setBases(BaseSpecs, NumGoodBases);
406
407 // Delete the remaining (good) base class specifiers, since their
408 // data has been copied into the CXXRecordDecl.
409 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
410 delete BaseSpecs[idx];
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000411}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000412
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000413//===----------------------------------------------------------------------===//
414// C++ class member Handling
415//===----------------------------------------------------------------------===//
416
417/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
418/// definition, when on C++.
419void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000420 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Douglas Gregor44b43212008-12-11 16:49:14 +0000421 PushDeclContext(S, Dcl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000422 FieldCollector->StartClass();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000423
424 if (Dcl->getIdentifier()) {
425 // C++ [class]p2:
426 // [...] The class-name is also inserted into the scope of the
427 // class itself; this is known as the injected-class-name. For
428 // purposes of access checking, the injected-class-name is treated
429 // as if it were a public member name.
Douglas Gregor510ffae2008-12-17 16:48:01 +0000430 PushOnScopeChains(CXXRecordDecl::Create(Context, Dcl->getTagKind(),
431 CurContext, Dcl->getLocation(),
432 Dcl->getIdentifier(), Dcl), S);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000433 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000434}
435
436/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
437/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
438/// bitfield width if there is one and 'InitExpr' specifies the initializer if
439/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
440/// declarators on it.
441///
Douglas Gregor72b505b2008-12-16 21:30:33 +0000442/// FIXME: The note below is out-of-date.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000443/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
444/// an instance field is declared, a new CXXFieldDecl is created but the method
445/// does *not* return it; it returns LastInGroup instead. The other C++ members
446/// (which are all ScopedDecls) are returned after appending them to
447/// LastInGroup.
448Sema::DeclTy *
449Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
450 ExprTy *BW, ExprTy *InitExpr,
451 DeclTy *LastInGroup) {
452 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000453 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000454 Expr *BitWidth = static_cast<Expr*>(BW);
455 Expr *Init = static_cast<Expr*>(InitExpr);
456 SourceLocation Loc = D.getIdentifierLoc();
457
Sebastian Redl669d5d72008-11-14 23:42:31 +0000458 bool isFunc = D.isFunctionDeclarator();
459
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000460 // C++ 9.2p6: A member shall not be declared to have automatic storage
461 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000462 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
463 // data members and cannot be applied to names declared const or static,
464 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000465 switch (DS.getStorageClassSpec()) {
466 case DeclSpec::SCS_unspecified:
467 case DeclSpec::SCS_typedef:
468 case DeclSpec::SCS_static:
469 // FALL THROUGH.
470 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000471 case DeclSpec::SCS_mutable:
472 if (isFunc) {
473 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000474 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000475 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000476 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
477
Sebastian Redla11f42f2008-11-17 23:24:37 +0000478 // FIXME: It would be nicer if the keyword was ignored only for this
479 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000480 D.getMutableDeclSpec().ClearStorageClassSpecs();
481 } else {
482 QualType T = GetTypeForDeclarator(D, S);
483 diag::kind err = static_cast<diag::kind>(0);
484 if (T->isReferenceType())
485 err = diag::err_mutable_reference;
486 else if (T.isConstQualified())
487 err = diag::err_mutable_const;
488 if (err != 0) {
489 if (DS.getStorageClassSpecLoc().isValid())
490 Diag(DS.getStorageClassSpecLoc(), err);
491 else
492 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000493 // FIXME: It would be nicer if the keyword was ignored only for this
494 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000495 D.getMutableDeclSpec().ClearStorageClassSpecs();
496 }
497 }
498 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000499 default:
500 if (DS.getStorageClassSpecLoc().isValid())
501 Diag(DS.getStorageClassSpecLoc(),
502 diag::err_storageclass_invalid_for_member);
503 else
504 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
505 D.getMutableDeclSpec().ClearStorageClassSpecs();
506 }
507
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000508 if (!isFunc &&
509 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
510 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000511 // Check also for this case:
512 //
513 // typedef int f();
514 // f a;
515 //
516 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
517 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
518 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000519
Sebastian Redl669d5d72008-11-14 23:42:31 +0000520 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
521 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000522 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000523
524 Decl *Member;
525 bool InvalidDecl = false;
526
527 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000528 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
529 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000530 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000531 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000532
533 if (!Member) return LastInGroup;
534
Douglas Gregor10bd3682008-11-17 22:58:34 +0000535 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000536
537 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
538 // specific methods. Use a wrapper class that can be used with all C++ class
539 // member decls.
540 CXXClassMemberWrapper(Member).setAccess(AS);
541
Douglas Gregor64bffa92008-11-05 16:20:31 +0000542 // C++ [dcl.init.aggr]p1:
543 // An aggregate is an array or a class (clause 9) with [...] no
544 // private or protected non-static data members (clause 11).
Sebastian Redl64b45f72009-01-05 20:52:13 +0000545 // A POD must be an aggregate.
546 if (isInstField && (AS == AS_private || AS == AS_protected)) {
547 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
548 Record->setAggregate(false);
549 Record->setPOD(false);
550 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000551
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000552 if (DS.isVirtualSpecified()) {
553 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
554 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
555 InvalidDecl = true;
556 } else {
557 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
558 CurClass->setAggregate(false);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000559 CurClass->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000560 CurClass->setPolymorphic(true);
561 }
562 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000563
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000564 if (BitWidth) {
565 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
566 // constant-expression be a value equal to zero.
567 // FIXME: Check this.
568
569 if (D.isFunctionDeclarator()) {
570 // FIXME: Emit diagnostic about only constructors taking base initializers
571 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000572 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000573 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000574 InvalidDecl = true;
575
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000576 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000577 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000578 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000579 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000580 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000581 InvalidDecl = true;
582 }
583
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000584 } else if (isa<FunctionDecl>(Member)) {
585 // A function typedef ("typedef int f(); f a;").
586 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000587 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000588 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000589 InvalidDecl = true;
590
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000591 } else if (isa<TypedefDecl>(Member)) {
592 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000593 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000594 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000595 InvalidDecl = true;
596
597 } else {
598 assert(isa<CXXClassVarDecl>(Member) &&
599 "Didn't we cover all member kinds?");
600 // C++ 9.6p3: A bit-field shall not be a static member.
601 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000602 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000603 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000604 InvalidDecl = true;
605 }
606 }
607
608 if (Init) {
609 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
610 // if it declares a static member of const integral or const enumeration
611 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000612 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
613 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000614 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000615 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000616 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
617 CVD->getType()->isIntegralType()) {
618 // constant-initializer
619 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000620 InvalidDecl = true;
621
622 } else {
623 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000624 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000625 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000626 InvalidDecl = true;
627 }
628
629 } else {
630 // not static member.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000631 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000632 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000633 InvalidDecl = true;
634 }
635 }
636
637 if (InvalidDecl)
638 Member->setInvalidDecl();
639
640 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000641 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000642 return LastInGroup;
643 }
644 return Member;
645}
646
Douglas Gregor7ad83902008-11-05 04:29:56 +0000647/// ActOnMemInitializer - Handle a C++ member initializer.
648Sema::MemInitResult
649Sema::ActOnMemInitializer(DeclTy *ConstructorD,
650 Scope *S,
651 IdentifierInfo *MemberOrBase,
652 SourceLocation IdLoc,
653 SourceLocation LParenLoc,
654 ExprTy **Args, unsigned NumArgs,
655 SourceLocation *CommaLocs,
656 SourceLocation RParenLoc) {
657 CXXConstructorDecl *Constructor
658 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
659 if (!Constructor) {
660 // The user wrote a constructor initializer on a function that is
661 // not a C++ constructor. Ignore the error for now, because we may
662 // have more member initializers coming; we'll diagnose it just
663 // once in ActOnMemInitializers.
664 return true;
665 }
666
667 CXXRecordDecl *ClassDecl = Constructor->getParent();
668
669 // C++ [class.base.init]p2:
670 // Names in a mem-initializer-id are looked up in the scope of the
671 // constructor’s class and, if not found in that scope, are looked
672 // up in the scope containing the constructor’s
673 // definition. [Note: if the constructor’s class contains a member
674 // with the same name as a direct or virtual base class of the
675 // class, a mem-initializer-id naming the member or base class and
676 // composed of a single identifier refers to the class member. A
677 // mem-initializer-id for the hidden base class may be specified
678 // using a qualified name. ]
679 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000680 FieldDecl *Member = 0;
681 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase);
682 if (Result.first != Result.second)
683 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000684
685 // FIXME: Handle members of an anonymous union.
686
687 if (Member) {
688 // FIXME: Perform direct initialization of the member.
689 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
690 }
691
692 // It didn't name a member, so see if it names a class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000693 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000694 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000695 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
696 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000697
698 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
699 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000700 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000701 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000702
703 // C++ [class.base.init]p2:
704 // [...] Unless the mem-initializer-id names a nonstatic data
705 // member of the constructor’s class or a direct or virtual base
706 // of that class, the mem-initializer is ill-formed. A
707 // mem-initializer-list can initialize a base class using any
708 // name that denotes that base class type.
709
710 // First, check for a direct base class.
711 const CXXBaseSpecifier *DirectBaseSpec = 0;
712 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
713 Base != ClassDecl->bases_end(); ++Base) {
714 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
715 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
716 // We found a direct base of this type. That's what we're
717 // initializing.
718 DirectBaseSpec = &*Base;
719 break;
720 }
721 }
722
723 // Check for a virtual base class.
724 // FIXME: We might be able to short-circuit this if we know in
725 // advance that there are no virtual bases.
726 const CXXBaseSpecifier *VirtualBaseSpec = 0;
727 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
728 // We haven't found a base yet; search the class hierarchy for a
729 // virtual base class.
730 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
731 /*DetectVirtual=*/false);
732 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
733 for (BasePaths::paths_iterator Path = Paths.begin();
734 Path != Paths.end(); ++Path) {
735 if (Path->back().Base->isVirtual()) {
736 VirtualBaseSpec = Path->back().Base;
737 break;
738 }
739 }
740 }
741 }
742
743 // C++ [base.class.init]p2:
744 // If a mem-initializer-id is ambiguous because it designates both
745 // a direct non-virtual base class and an inherited virtual base
746 // class, the mem-initializer is ill-formed.
747 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000748 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
749 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000750
751 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
752}
753
754
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000755void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
756 DeclTy *TagDecl,
757 SourceLocation LBrac,
758 SourceLocation RBrac) {
759 ActOnFields(S, RLoc, TagDecl,
760 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000761 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor61366e92008-12-24 00:01:03 +0000762 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000763}
764
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000765/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
766/// special functions, such as the default constructor, copy
767/// constructor, or destructor, to the given C++ class (C++
768/// [special]p1). This routine can only be executed just before the
769/// definition of the class is complete.
770void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000771 QualType ClassType = Context.getTypeDeclType(ClassDecl);
772 ClassType = Context.getCanonicalType(ClassType);
773
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000774 if (!ClassDecl->hasUserDeclaredConstructor()) {
775 // C++ [class.ctor]p5:
776 // A default constructor for a class X is a constructor of class X
777 // that can be called without an argument. If there is no
778 // user-declared constructor for class X, a default constructor is
779 // implicitly declared. An implicitly-declared default constructor
780 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000781 DeclarationName Name
782 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000783 CXXConstructorDecl *DefaultCon =
784 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000785 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000786 Context.getFunctionType(Context.VoidTy,
787 0, 0, false, 0),
788 /*isExplicit=*/false,
789 /*isInline=*/true,
790 /*isImplicitlyDeclared=*/true);
791 DefaultCon->setAccess(AS_public);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000792 ClassDecl->addDecl(Context, DefaultCon);
793
794 // Notify the class that we've added a constructor.
795 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000796 }
797
798 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
799 // C++ [class.copy]p4:
800 // If the class definition does not explicitly declare a copy
801 // constructor, one is declared implicitly.
802
803 // C++ [class.copy]p5:
804 // The implicitly-declared copy constructor for a class X will
805 // have the form
806 //
807 // X::X(const X&)
808 //
809 // if
810 bool HasConstCopyConstructor = true;
811
812 // -- each direct or virtual base class B of X has a copy
813 // constructor whose first parameter is of type const B& or
814 // const volatile B&, and
815 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
816 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
817 const CXXRecordDecl *BaseClassDecl
818 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
819 HasConstCopyConstructor
820 = BaseClassDecl->hasConstCopyConstructor(Context);
821 }
822
823 // -- for all the nonstatic data members of X that are of a
824 // class type M (or array thereof), each such class type
825 // has a copy constructor whose first parameter is of type
826 // const M& or const volatile M&.
827 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
828 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
829 QualType FieldType = (*Field)->getType();
830 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
831 FieldType = Array->getElementType();
832 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
833 const CXXRecordDecl *FieldClassDecl
834 = cast<CXXRecordDecl>(FieldClassType->getDecl());
835 HasConstCopyConstructor
836 = FieldClassDecl->hasConstCopyConstructor(Context);
837 }
838 }
839
Sebastian Redl64b45f72009-01-05 20:52:13 +0000840 // Otherwise, the implicitly declared copy constructor will have
841 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000842 //
843 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +0000844 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000845 if (HasConstCopyConstructor)
846 ArgType = ArgType.withConst();
847 ArgType = Context.getReferenceType(ArgType);
848
Sebastian Redl64b45f72009-01-05 20:52:13 +0000849 // An implicitly-declared copy constructor is an inline public
850 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000851 DeclarationName Name
852 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000853 CXXConstructorDecl *CopyConstructor
854 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000855 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000856 Context.getFunctionType(Context.VoidTy,
857 &ArgType, 1,
858 false, 0),
859 /*isExplicit=*/false,
860 /*isInline=*/true,
861 /*isImplicitlyDeclared=*/true);
862 CopyConstructor->setAccess(AS_public);
863
864 // Add the parameter to the constructor.
865 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
866 ClassDecl->getLocation(),
867 /*IdentifierInfo=*/0,
868 ArgType, VarDecl::None, 0, 0);
869 CopyConstructor->setParams(&FromParam, 1);
870
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000871 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000872 ClassDecl->addDecl(Context, CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000873 }
874
Sebastian Redl64b45f72009-01-05 20:52:13 +0000875 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
876 // Note: The following rules are largely analoguous to the copy
877 // constructor rules. Note that virtual bases are not taken into account
878 // for determining the argument type of the operator. Note also that
879 // operators taking an object instead of a reference are allowed.
880 //
881 // C++ [class.copy]p10:
882 // If the class definition does not explicitly declare a copy
883 // assignment operator, one is declared implicitly.
884 // The implicitly-defined copy assignment operator for a class X
885 // will have the form
886 //
887 // X& X::operator=(const X&)
888 //
889 // if
890 bool HasConstCopyAssignment = true;
891
892 // -- each direct base class B of X has a copy assignment operator
893 // whose parameter is of type const B&, const volatile B& or B,
894 // and
895 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
896 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
897 const CXXRecordDecl *BaseClassDecl
898 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
899 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
900 }
901
902 // -- for all the nonstatic data members of X that are of a class
903 // type M (or array thereof), each such class type has a copy
904 // assignment operator whose parameter is of type const M&,
905 // const volatile M& or M.
906 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
907 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
908 QualType FieldType = (*Field)->getType();
909 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
910 FieldType = Array->getElementType();
911 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
912 const CXXRecordDecl *FieldClassDecl
913 = cast<CXXRecordDecl>(FieldClassType->getDecl());
914 HasConstCopyAssignment
915 = FieldClassDecl->hasConstCopyAssignment(Context);
916 }
917 }
918
919 // Otherwise, the implicitly declared copy assignment operator will
920 // have the form
921 //
922 // X& X::operator=(X&)
923 QualType ArgType = ClassType;
924 QualType RetType = Context.getReferenceType(ArgType);
925 if (HasConstCopyAssignment)
926 ArgType = ArgType.withConst();
927 ArgType = Context.getReferenceType(ArgType);
928
929 // An implicitly-declared copy assignment operator is an inline public
930 // member of its class.
931 DeclarationName Name =
932 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
933 CXXMethodDecl *CopyAssignment =
934 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
935 Context.getFunctionType(RetType, &ArgType, 1,
936 false, 0),
937 /*isStatic=*/false, /*isInline=*/true, 0);
938 CopyAssignment->setAccess(AS_public);
939
940 // Add the parameter to the operator.
941 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
942 ClassDecl->getLocation(),
943 /*IdentifierInfo=*/0,
944 ArgType, VarDecl::None, 0, 0);
945 CopyAssignment->setParams(&FromParam, 1);
946
947 // Don't call addedAssignmentOperator. There is no way to distinguish an
948 // implicit from an explicit assignment operator.
949 ClassDecl->addDecl(Context, CopyAssignment);
950 }
951
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000952 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000953 // C++ [class.dtor]p2:
954 // If a class has no user-declared destructor, a destructor is
955 // declared implicitly. An implicitly-declared destructor is an
956 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000957 DeclarationName Name
958 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000959 CXXDestructorDecl *Destructor
960 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000961 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000962 Context.getFunctionType(Context.VoidTy,
963 0, 0, false, 0),
964 /*isInline=*/true,
965 /*isImplicitlyDeclared=*/true);
966 Destructor->setAccess(AS_public);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000967 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000968 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000969}
970
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000971void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000972 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000973 FieldCollector->FinishClass();
974 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000975
976 // Everything, including inline method definitions, have been parsed.
977 // Let the consumer know of the new TagDecl definition.
978 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000979}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000980
Douglas Gregor72b505b2008-12-16 21:30:33 +0000981/// ActOnStartDelayedCXXMethodDeclaration - We have completed
982/// parsing a top-level (non-nested) C++ class, and we are now
983/// parsing those parts of the given Method declaration that could
984/// not be parsed earlier (C++ [class.mem]p2), such as default
985/// arguments. This action should enter the scope of the given
986/// Method declaration as if we had just parsed the qualified method
987/// name. However, it should not bring the parameters into scope;
988/// that will be performed by ActOnDelayedCXXMethodParameter.
989void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
990 CXXScopeSpec SS;
991 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
992 ActOnCXXEnterDeclaratorScope(S, SS);
993}
994
995/// ActOnDelayedCXXMethodParameter - We've already started a delayed
996/// C++ method declaration. We're (re-)introducing the given
997/// function parameter into scope for use in parsing later parts of
998/// the method declaration. For example, we could see an
999/// ActOnParamDefaultArgument event for this parameter.
1000void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1001 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +00001002
1003 // If this parameter has an unparsed default argument, clear it out
1004 // to make way for the parsed default argument.
1005 if (Param->hasUnparsedDefaultArg())
1006 Param->setDefaultArg(0);
1007
Douglas Gregor72b505b2008-12-16 21:30:33 +00001008 S->AddDecl(Param);
1009 if (Param->getDeclName())
1010 IdResolver.AddDecl(Param);
1011}
1012
1013/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1014/// processing the delayed method declaration for Method. The method
1015/// declaration is now considered finished. There may be a separate
1016/// ActOnStartOfFunctionDef action later (not necessarily
1017/// immediately!) for this method, if it was also defined inside the
1018/// class body.
1019void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1020 FunctionDecl *Method = (FunctionDecl*)MethodD;
1021 CXXScopeSpec SS;
1022 SS.setScopeRep(Method->getDeclContext());
1023 ActOnCXXExitDeclaratorScope(S, SS);
1024
1025 // Now that we have our default arguments, check the constructor
1026 // again. It could produce additional diagnostics or affect whether
1027 // the class has implicitly-declared destructors, among other
1028 // things.
1029 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1030 if (CheckConstructor(Constructor))
1031 Constructor->setInvalidDecl();
1032 }
1033
1034 // Check the default arguments, which we may have added.
1035 if (!Method->isInvalidDecl())
1036 CheckCXXDefaultArguments(Method);
1037}
1038
Douglas Gregor42a552f2008-11-05 20:51:48 +00001039/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001040/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001041/// R. If there are any errors in the declarator, this routine will
1042/// emit diagnostics and return true. Otherwise, it will return
1043/// false. Either way, the type @p R will be updated to reflect a
1044/// well-formed type for the constructor.
1045bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1046 FunctionDecl::StorageClass& SC) {
1047 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1048 bool isInvalid = false;
1049
1050 // C++ [class.ctor]p3:
1051 // A constructor shall not be virtual (10.3) or static (9.4). A
1052 // constructor can be invoked for a const, volatile or const
1053 // volatile object. A constructor shall not be declared const,
1054 // volatile, or const volatile (9.3.2).
1055 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001056 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1057 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1058 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001059 isInvalid = true;
1060 }
1061 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001062 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1063 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1064 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001065 isInvalid = true;
1066 SC = FunctionDecl::None;
1067 }
1068 if (D.getDeclSpec().hasTypeSpecifier()) {
1069 // Constructors don't have return types, but the parser will
1070 // happily parse something like:
1071 //
1072 // class X {
1073 // float X(float);
1074 // };
1075 //
1076 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001077 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1078 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1079 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001080 }
1081 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1082 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1083 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001084 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1085 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001086 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001087 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1088 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001089 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001090 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1091 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001092 }
1093
1094 // Rebuild the function type "R" without any type qualifiers (in
1095 // case any of the errors above fired) and with "void" as the
1096 // return type, since constructors don't have return types. We
1097 // *always* have to do this, because GetTypeForDeclarator will
1098 // put in a result type of "int" when none was specified.
1099 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1100 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1101 Proto->getNumArgs(),
1102 Proto->isVariadic(),
1103 0);
1104
1105 return isInvalid;
1106}
1107
Douglas Gregor72b505b2008-12-16 21:30:33 +00001108/// CheckConstructor - Checks a fully-formed constructor for
1109/// well-formedness, issuing any diagnostics required. Returns true if
1110/// the constructor declarator is invalid.
1111bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1112 if (Constructor->isInvalidDecl())
1113 return true;
1114
1115 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1116 bool Invalid = false;
1117
1118 // C++ [class.copy]p3:
1119 // A declaration of a constructor for a class X is ill-formed if
1120 // its first parameter is of type (optionally cv-qualified) X and
1121 // either there are no other parameters or else all other
1122 // parameters have default arguments.
1123 if ((Constructor->getNumParams() == 1) ||
1124 (Constructor->getNumParams() > 1 &&
1125 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1126 QualType ParamType = Constructor->getParamDecl(0)->getType();
1127 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1128 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1129 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1130 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1131 Invalid = true;
1132 }
1133 }
1134
1135 // Notify the class that we've added a constructor.
1136 ClassDecl->addedConstructor(Context, Constructor);
1137
1138 return Invalid;
1139}
1140
Douglas Gregor42a552f2008-11-05 20:51:48 +00001141/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1142/// the well-formednes of the destructor declarator @p D with type @p
1143/// R. If there are any errors in the declarator, this routine will
1144/// emit diagnostics and return true. Otherwise, it will return
1145/// false. Either way, the type @p R will be updated to reflect a
1146/// well-formed type for the destructor.
1147bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1148 FunctionDecl::StorageClass& SC) {
1149 bool isInvalid = false;
1150
1151 // C++ [class.dtor]p1:
1152 // [...] A typedef-name that names a class is a class-name
1153 // (7.1.3); however, a typedef-name that names a class shall not
1154 // be used as the identifier in the declarator for a destructor
1155 // declaration.
1156 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1157 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001158 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 << TypedefD->getDeclName();
Douglas Gregor55c60952008-11-10 14:41:22 +00001160 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001161 }
1162
1163 // C++ [class.dtor]p2:
1164 // A destructor is used to destroy objects of its class type. A
1165 // destructor takes no parameters, and no return type can be
1166 // specified for it (not even void). The address of a destructor
1167 // shall not be taken. A destructor shall not be static. A
1168 // destructor can be invoked for a const, volatile or const
1169 // volatile object. A destructor shall not be declared const,
1170 // volatile or const volatile (9.3.2).
1171 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001172 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1173 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1174 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001175 isInvalid = true;
1176 SC = FunctionDecl::None;
1177 }
1178 if (D.getDeclSpec().hasTypeSpecifier()) {
1179 // Destructors don't have return types, but the parser will
1180 // happily parse something like:
1181 //
1182 // class X {
1183 // float ~X();
1184 // };
1185 //
1186 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001187 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1188 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1189 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001190 }
1191 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1192 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1193 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001194 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1195 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001196 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001197 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1198 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001199 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001200 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1201 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001202 }
1203
1204 // Make sure we don't have any parameters.
1205 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1206 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1207
1208 // Delete the parameters.
1209 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1210 if (FTI.NumArgs) {
1211 delete [] FTI.ArgInfo;
1212 FTI.NumArgs = 0;
1213 FTI.ArgInfo = 0;
1214 }
1215 }
1216
1217 // Make sure the destructor isn't variadic.
1218 if (R->getAsFunctionTypeProto()->isVariadic())
1219 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1220
1221 // Rebuild the function type "R" without any type qualifiers or
1222 // parameters (in case any of the errors above fired) and with
1223 // "void" as the return type, since destructors don't have return
1224 // types. We *always* have to do this, because GetTypeForDeclarator
1225 // will put in a result type of "int" when none was specified.
1226 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1227
1228 return isInvalid;
1229}
1230
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001231/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1232/// well-formednes of the conversion function declarator @p D with
1233/// type @p R. If there are any errors in the declarator, this routine
1234/// will emit diagnostics and return true. Otherwise, it will return
1235/// false. Either way, the type @p R will be updated to reflect a
1236/// well-formed type for the conversion operator.
1237bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1238 FunctionDecl::StorageClass& SC) {
1239 bool isInvalid = false;
1240
1241 // C++ [class.conv.fct]p1:
1242 // Neither parameter types nor return type can be specified. The
1243 // type of a conversion function (8.3.5) is “function taking no
1244 // parameter returning conversion-type-id.”
1245 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001246 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1247 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1248 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001249 isInvalid = true;
1250 SC = FunctionDecl::None;
1251 }
1252 if (D.getDeclSpec().hasTypeSpecifier()) {
1253 // Conversion functions don't have return types, but the parser will
1254 // happily parse something like:
1255 //
1256 // class X {
1257 // float operator bool();
1258 // };
1259 //
1260 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001261 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1262 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1263 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001264 }
1265
1266 // Make sure we don't have any parameters.
1267 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1268 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1269
1270 // Delete the parameters.
1271 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1272 if (FTI.NumArgs) {
1273 delete [] FTI.ArgInfo;
1274 FTI.NumArgs = 0;
1275 FTI.ArgInfo = 0;
1276 }
1277 }
1278
1279 // Make sure the conversion function isn't variadic.
1280 if (R->getAsFunctionTypeProto()->isVariadic())
1281 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1282
1283 // C++ [class.conv.fct]p4:
1284 // The conversion-type-id shall not represent a function type nor
1285 // an array type.
1286 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1287 if (ConvType->isArrayType()) {
1288 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1289 ConvType = Context.getPointerType(ConvType);
1290 } else if (ConvType->isFunctionType()) {
1291 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1292 ConvType = Context.getPointerType(ConvType);
1293 }
1294
1295 // Rebuild the function type "R" without any parameters (in case any
1296 // of the errors above fired) and with the conversion type as the
1297 // return type.
1298 R = Context.getFunctionType(ConvType, 0, 0, false,
1299 R->getAsFunctionTypeProto()->getTypeQuals());
1300
1301 return isInvalid;
1302}
1303
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001304/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1305/// the declaration of the given C++ conversion function. This routine
1306/// is responsible for recording the conversion function in the C++
1307/// class, if possible.
1308Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1309 assert(Conversion && "Expected to receive a conversion function declaration");
1310
Douglas Gregor9d350972008-12-12 08:25:50 +00001311 // Set the lexical context of this conversion function
1312 Conversion->setLexicalDeclContext(CurContext);
1313
1314 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001315
1316 // Make sure we aren't redeclaring the conversion function.
1317 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001318
1319 // C++ [class.conv.fct]p1:
1320 // [...] A conversion function is never used to convert a
1321 // (possibly cv-qualified) object to the (possibly cv-qualified)
1322 // same object type (or a reference to it), to a (possibly
1323 // cv-qualified) base class of that type (or a reference to it),
1324 // or to (possibly cv-qualified) void.
1325 // FIXME: Suppress this warning if the conversion function ends up
1326 // being a virtual function that overrides a virtual function in a
1327 // base class.
1328 QualType ClassType
1329 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1330 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1331 ConvType = ConvTypeRef->getPointeeType();
1332 if (ConvType->isRecordType()) {
1333 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1334 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001335 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001336 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001337 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001338 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001339 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001340 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001341 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001342 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001343 }
1344
Douglas Gregor70316a02008-12-26 15:00:45 +00001345 if (Conversion->getPreviousDeclaration()) {
1346 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1347 for (OverloadedFunctionDecl::function_iterator
1348 Conv = Conversions->function_begin(),
1349 ConvEnd = Conversions->function_end();
1350 Conv != ConvEnd; ++Conv) {
1351 if (*Conv == Conversion->getPreviousDeclaration()) {
1352 *Conv = Conversion;
1353 return (DeclTy *)Conversion;
1354 }
1355 }
1356 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1357 } else
1358 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001359
1360 return (DeclTy *)Conversion;
1361}
1362
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001363//===----------------------------------------------------------------------===//
1364// Namespace Handling
1365//===----------------------------------------------------------------------===//
1366
1367/// ActOnStartNamespaceDef - This is called at the start of a namespace
1368/// definition.
1369Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1370 SourceLocation IdentLoc,
1371 IdentifierInfo *II,
1372 SourceLocation LBrace) {
1373 NamespaceDecl *Namespc =
1374 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1375 Namespc->setLBracLoc(LBrace);
1376
1377 Scope *DeclRegionScope = NamespcScope->getParent();
1378
1379 if (II) {
1380 // C++ [namespace.def]p2:
1381 // The identifier in an original-namespace-definition shall not have been
1382 // previously defined in the declarative region in which the
1383 // original-namespace-definition appears. The identifier in an
1384 // original-namespace-definition is the name of the namespace. Subsequently
1385 // in that declarative region, it is treated as an original-namespace-name.
1386
1387 Decl *PrevDecl =
Douglas Gregor44b43212008-12-11 16:49:14 +00001388 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1389 /*enableLazyBuiltinCreation=*/false,
1390 /*LookupInParent=*/false);
1391
1392 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1393 // This is an extended namespace definition.
1394 // Attach this namespace decl to the chain of extended namespace
1395 // definitions.
1396 OrigNS->setNextNamespace(Namespc);
1397 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001398
Douglas Gregor44b43212008-12-11 16:49:14 +00001399 // Remove the previous declaration from the scope.
1400 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001401 IdResolver.RemoveDecl(OrigNS);
1402 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001403 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001404 } else if (PrevDecl) {
1405 // This is an invalid name redefinition.
1406 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1407 << Namespc->getDeclName();
1408 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1409 Namespc->setInvalidDecl();
1410 // Continue on to push Namespc as current DeclContext and return it.
1411 }
1412
1413 PushOnScopeChains(Namespc, DeclRegionScope);
1414 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001415 // FIXME: Handle anonymous namespaces
1416 }
1417
1418 // Although we could have an invalid decl (i.e. the namespace name is a
1419 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001420 // FIXME: We should be able to push Namespc here, so that the
1421 // each DeclContext for the namespace has the declarations
1422 // that showed up in that particular namespace definition.
1423 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001424 return Namespc;
1425}
1426
1427/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1428/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1429void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1430 Decl *Dcl = static_cast<Decl *>(D);
1431 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1432 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1433 Namespc->setRBracLoc(RBrace);
1434 PopDeclContext();
1435}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001436
Douglas Gregorf780abc2008-12-30 03:27:21 +00001437Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1438 SourceLocation UsingLoc,
1439 SourceLocation NamespcLoc,
1440 const CXXScopeSpec &SS,
1441 SourceLocation IdentLoc,
1442 IdentifierInfo *NamespcName,
1443 AttributeList *AttrList) {
1444 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1445 assert(NamespcName && "Invalid NamespcName.");
1446 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1447
1448 // FIXME: This still requires lot more checks, and AST support.
1449 // Lookup namespace name.
1450 DeclContext *DC = static_cast<DeclContext*>(SS.getScopeRep());
1451 Decl *NS = 0;
1452
1453 if ((NS = LookupNamespaceName(NamespcName, S, DC))) {
1454 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1455 } else {
1456 DiagnosticBuilder Builder = Diag(IdentLoc, diag::err_expected_namespace_name);
1457 if (SS.isSet())
1458 Builder << SS.getRange();
1459 }
1460
1461 // FIXME: We ignore AttrList for now, and delete it to avoid leak.
1462 delete AttrList;
1463 return 0;
1464}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001465
1466/// AddCXXDirectInitializerToDecl - This action is called immediately after
1467/// ActOnDeclarator, when a C++ direct initializer is present.
1468/// e.g: "int x(1);"
1469void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1470 ExprTy **ExprTys, unsigned NumExprs,
1471 SourceLocation *CommaLocs,
1472 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001473 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001474 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001475
1476 // If there is no declaration, there was an error parsing it. Just ignore
1477 // the initializer.
1478 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001479 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001480 delete static_cast<Expr *>(ExprTys[i]);
1481 return;
1482 }
1483
1484 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1485 if (!VDecl) {
1486 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1487 RealDecl->setInvalidDecl();
1488 return;
1489 }
1490
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001491 // We will treat direct-initialization as a copy-initialization:
1492 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001493 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1494 //
1495 // Clients that want to distinguish between the two forms, can check for
1496 // direct initializer using VarDecl::hasCXXDirectInitializer().
1497 // A major benefit is that clients that don't particularly care about which
1498 // exactly form was it (like the CodeGen) can handle both cases without
1499 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001500
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001501 // C++ 8.5p11:
1502 // The form of initialization (using parentheses or '=') is generally
1503 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001504 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001505 QualType DeclInitType = VDecl->getType();
1506 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1507 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001508
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001509 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001510 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001511 = PerformInitializationByConstructor(DeclInitType,
1512 (Expr **)ExprTys, NumExprs,
1513 VDecl->getLocation(),
1514 SourceRange(VDecl->getLocation(),
1515 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001516 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001517 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001518 if (!Constructor) {
1519 RealDecl->setInvalidDecl();
1520 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001521
1522 // Let clients know that initialization was done with a direct
1523 // initializer.
1524 VDecl->setCXXDirectInitializer(true);
1525
1526 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1527 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001528 return;
1529 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001530
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001531 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001532 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1533 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001534 RealDecl->setInvalidDecl();
1535 return;
1536 }
1537
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001538 // Let clients know that initialization was done with a direct initializer.
1539 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001540
1541 assert(NumExprs == 1 && "Expected 1 expression");
1542 // Set the init expression, handles conversions.
Sebastian Redl798d1192008-12-13 16:23:55 +00001543 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001544}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001545
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001546/// PerformInitializationByConstructor - Perform initialization by
1547/// constructor (C++ [dcl.init]p14), which may occur as part of
1548/// direct-initialization or copy-initialization. We are initializing
1549/// an object of type @p ClassType with the given arguments @p
1550/// Args. @p Loc is the location in the source code where the
1551/// initializer occurs (e.g., a declaration, member initializer,
1552/// functional cast, etc.) while @p Range covers the whole
1553/// initialization. @p InitEntity is the entity being initialized,
1554/// which may by the name of a declaration or a type. @p Kind is the
1555/// kind of initialization we're performing, which affects whether
1556/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001557/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001558/// when the initialization fails, emits a diagnostic and returns
1559/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001560CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001561Sema::PerformInitializationByConstructor(QualType ClassType,
1562 Expr **Args, unsigned NumArgs,
1563 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001564 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001565 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001566 const RecordType *ClassRec = ClassType->getAsRecordType();
1567 assert(ClassRec && "Can only initialize a class type here");
1568
1569 // C++ [dcl.init]p14:
1570 //
1571 // If the initialization is direct-initialization, or if it is
1572 // copy-initialization where the cv-unqualified version of the
1573 // source type is the same class as, or a derived class of, the
1574 // class of the destination, constructors are considered. The
1575 // applicable constructors are enumerated (13.3.1.3), and the
1576 // best one is chosen through overload resolution (13.3). The
1577 // constructor so selected is called to initialize the object,
1578 // with the initializer expression(s) as its argument(s). If no
1579 // constructor applies, or the overload resolution is ambiguous,
1580 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001581 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1582 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001583
1584 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001585 DeclarationName ConstructorName
1586 = Context.DeclarationNames.getCXXConstructorName(
1587 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001588 DeclContext::lookup_const_iterator Con, ConEnd;
1589 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(Context, ConstructorName);
1590 Con != ConEnd; ++Con) {
1591 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001592 if ((Kind == IK_Direct) ||
1593 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1594 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1595 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1596 }
1597
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001598 // FIXME: When we decide not to synthesize the implicitly-declared
1599 // constructors, we'll need to make them appear here.
1600
Douglas Gregor18fe5682008-11-03 20:45:27 +00001601 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001602 switch (BestViableFunction(CandidateSet, Best)) {
1603 case OR_Success:
1604 // We found a constructor. Return it.
1605 return cast<CXXConstructorDecl>(Best->Function);
1606
1607 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001608 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1609 << InitEntity << (unsigned)CandidateSet.size() << Range;
1610 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001611 return 0;
1612
1613 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001614 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001615 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1616 return 0;
1617 }
1618
1619 return 0;
1620}
1621
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001622/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1623/// determine whether they are reference-related,
1624/// reference-compatible, reference-compatible with added
1625/// qualification, or incompatible, for use in C++ initialization by
1626/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1627/// type, and the first type (T1) is the pointee type of the reference
1628/// type being initialized.
1629Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001630Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1631 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001632 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1633 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1634
1635 T1 = Context.getCanonicalType(T1);
1636 T2 = Context.getCanonicalType(T2);
1637 QualType UnqualT1 = T1.getUnqualifiedType();
1638 QualType UnqualT2 = T2.getUnqualifiedType();
1639
1640 // C++ [dcl.init.ref]p4:
1641 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1642 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1643 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001644 if (UnqualT1 == UnqualT2)
1645 DerivedToBase = false;
1646 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1647 DerivedToBase = true;
1648 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001649 return Ref_Incompatible;
1650
1651 // At this point, we know that T1 and T2 are reference-related (at
1652 // least).
1653
1654 // C++ [dcl.init.ref]p4:
1655 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1656 // reference-related to T2 and cv1 is the same cv-qualification
1657 // as, or greater cv-qualification than, cv2. For purposes of
1658 // overload resolution, cases for which cv1 is greater
1659 // cv-qualification than cv2 are identified as
1660 // reference-compatible with added qualification (see 13.3.3.2).
1661 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1662 return Ref_Compatible;
1663 else if (T1.isMoreQualifiedThan(T2))
1664 return Ref_Compatible_With_Added_Qualification;
1665 else
1666 return Ref_Related;
1667}
1668
1669/// CheckReferenceInit - Check the initialization of a reference
1670/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1671/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001672/// list), and DeclType is the type of the declaration. When ICS is
1673/// non-null, this routine will compute the implicit conversion
1674/// sequence according to C++ [over.ics.ref] and will not produce any
1675/// diagnostics; when ICS is null, it will emit diagnostics when any
1676/// errors are found. Either way, a return value of true indicates
1677/// that there was a failure, a return value of false indicates that
1678/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001679///
1680/// When @p SuppressUserConversions, user-defined conversions are
1681/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001682bool
1683Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001684 ImplicitConversionSequence *ICS,
1685 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001686 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1687
1688 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1689 QualType T2 = Init->getType();
1690
Douglas Gregor904eed32008-11-10 20:40:00 +00001691 // If the initializer is the address of an overloaded function, try
1692 // to resolve the overloaded function. If all goes well, T2 is the
1693 // type of the resulting function.
1694 if (T2->isOverloadType()) {
1695 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1696 ICS != 0);
1697 if (Fn) {
1698 // Since we're performing this reference-initialization for
1699 // real, update the initializer with the resulting function.
1700 if (!ICS)
1701 FixOverloadedFunctionReference(Init, Fn);
1702
1703 T2 = Fn->getType();
1704 }
1705 }
1706
Douglas Gregor15da57e2008-10-29 02:00:59 +00001707 // Compute some basic properties of the types and the initializer.
1708 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001709 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001710 ReferenceCompareResult RefRelationship
1711 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1712
1713 // Most paths end in a failed conversion.
1714 if (ICS)
1715 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001716
1717 // C++ [dcl.init.ref]p5:
1718 // A reference to type “cv1 T1” is initialized by an expression
1719 // of type “cv2 T2” as follows:
1720
1721 // -- If the initializer expression
1722
1723 bool BindsDirectly = false;
1724 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1725 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001726 //
1727 // Note that the bit-field check is skipped if we are just computing
1728 // the implicit conversion sequence (C++ [over.best.ics]p2).
1729 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1730 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001731 BindsDirectly = true;
1732
Douglas Gregor15da57e2008-10-29 02:00:59 +00001733 if (ICS) {
1734 // C++ [over.ics.ref]p1:
1735 // When a parameter of reference type binds directly (8.5.3)
1736 // to an argument expression, the implicit conversion sequence
1737 // is the identity conversion, unless the argument expression
1738 // has a type that is a derived class of the parameter type,
1739 // in which case the implicit conversion sequence is a
1740 // derived-to-base Conversion (13.3.3.1).
1741 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1742 ICS->Standard.First = ICK_Identity;
1743 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1744 ICS->Standard.Third = ICK_Identity;
1745 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1746 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001747 ICS->Standard.ReferenceBinding = true;
1748 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001749
1750 // Nothing more to do: the inaccessibility/ambiguity check for
1751 // derived-to-base conversions is suppressed when we're
1752 // computing the implicit conversion sequence (C++
1753 // [over.best.ics]p2).
1754 return false;
1755 } else {
1756 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001757 // FIXME: Binding to a subobject of the lvalue is going to require
1758 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001759 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001760 }
1761 }
1762
1763 // -- has a class type (i.e., T2 is a class type) and can be
1764 // implicitly converted to an lvalue of type “cv3 T3,”
1765 // where “cv1 T1” is reference-compatible with “cv3 T3”
1766 // 92) (this conversion is selected by enumerating the
1767 // applicable conversion functions (13.3.1.6) and choosing
1768 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001769 if (!SuppressUserConversions && T2->isRecordType()) {
1770 // FIXME: Look for conversions in base classes!
1771 CXXRecordDecl *T2RecordDecl
1772 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001773
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001774 OverloadCandidateSet CandidateSet;
1775 OverloadedFunctionDecl *Conversions
1776 = T2RecordDecl->getConversionFunctions();
1777 for (OverloadedFunctionDecl::function_iterator Func
1778 = Conversions->function_begin();
1779 Func != Conversions->function_end(); ++Func) {
1780 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1781
1782 // If the conversion function doesn't return a reference type,
1783 // it can't be considered for this conversion.
1784 // FIXME: This will change when we support rvalue references.
1785 if (Conv->getConversionType()->isReferenceType())
1786 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1787 }
1788
1789 OverloadCandidateSet::iterator Best;
1790 switch (BestViableFunction(CandidateSet, Best)) {
1791 case OR_Success:
1792 // This is a direct binding.
1793 BindsDirectly = true;
1794
1795 if (ICS) {
1796 // C++ [over.ics.ref]p1:
1797 //
1798 // [...] If the parameter binds directly to the result of
1799 // applying a conversion function to the argument
1800 // expression, the implicit conversion sequence is a
1801 // user-defined conversion sequence (13.3.3.1.2), with the
1802 // second standard conversion sequence either an identity
1803 // conversion or, if the conversion function returns an
1804 // entity of a type that is a derived class of the parameter
1805 // type, a derived-to-base Conversion.
1806 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1807 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1808 ICS->UserDefined.After = Best->FinalConversion;
1809 ICS->UserDefined.ConversionFunction = Best->Function;
1810 assert(ICS->UserDefined.After.ReferenceBinding &&
1811 ICS->UserDefined.After.DirectBinding &&
1812 "Expected a direct reference binding!");
1813 return false;
1814 } else {
1815 // Perform the conversion.
1816 // FIXME: Binding to a subobject of the lvalue is going to require
1817 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001818 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001819 }
1820 break;
1821
1822 case OR_Ambiguous:
1823 assert(false && "Ambiguous reference binding conversions not implemented.");
1824 return true;
1825
1826 case OR_No_Viable_Function:
1827 // There was no suitable conversion; continue with other checks.
1828 break;
1829 }
1830 }
1831
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001832 if (BindsDirectly) {
1833 // C++ [dcl.init.ref]p4:
1834 // [...] In all cases where the reference-related or
1835 // reference-compatible relationship of two types is used to
1836 // establish the validity of a reference binding, and T1 is a
1837 // base class of T2, a program that necessitates such a binding
1838 // is ill-formed if T1 is an inaccessible (clause 11) or
1839 // ambiguous (10.2) base class of T2.
1840 //
1841 // Note that we only check this condition when we're allowed to
1842 // complain about errors, because we should not be checking for
1843 // ambiguity (or inaccessibility) unless the reference binding
1844 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001845 if (DerivedToBase)
1846 return CheckDerivedToBaseConversion(T2, T1,
1847 Init->getSourceRange().getBegin(),
1848 Init->getSourceRange());
1849 else
1850 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001851 }
1852
1853 // -- Otherwise, the reference shall be to a non-volatile const
1854 // type (i.e., cv1 shall be const).
1855 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001856 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001857 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001858 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001859 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1860 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001861 return true;
1862 }
1863
1864 // -- If the initializer expression is an rvalue, with T2 a
1865 // class type, and “cv1 T1” is reference-compatible with
1866 // “cv2 T2,” the reference is bound in one of the
1867 // following ways (the choice is implementation-defined):
1868 //
1869 // -- The reference is bound to the object represented by
1870 // the rvalue (see 3.10) or to a sub-object within that
1871 // object.
1872 //
1873 // -- A temporary of type “cv1 T2” [sic] is created, and
1874 // a constructor is called to copy the entire rvalue
1875 // object into the temporary. The reference is bound to
1876 // the temporary or to a sub-object within the
1877 // temporary.
1878 //
1879 //
1880 // The constructor that would be used to make the copy
1881 // shall be callable whether or not the copy is actually
1882 // done.
1883 //
1884 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1885 // freedom, so we will always take the first option and never build
1886 // a temporary in this case. FIXME: We will, however, have to check
1887 // for the presence of a copy constructor in C++98/03 mode.
1888 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001889 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1890 if (ICS) {
1891 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1892 ICS->Standard.First = ICK_Identity;
1893 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1894 ICS->Standard.Third = ICK_Identity;
1895 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1896 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001897 ICS->Standard.ReferenceBinding = true;
1898 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001899 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001900 // FIXME: Binding to a subobject of the rvalue is going to require
1901 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001902 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001903 }
1904 return false;
1905 }
1906
1907 // -- Otherwise, a temporary of type “cv1 T1” is created and
1908 // initialized from the initializer expression using the
1909 // rules for a non-reference copy initialization (8.5). The
1910 // reference is then bound to the temporary. If T1 is
1911 // reference-related to T2, cv1 must be the same
1912 // cv-qualification as, or greater cv-qualification than,
1913 // cv2; otherwise, the program is ill-formed.
1914 if (RefRelationship == Ref_Related) {
1915 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1916 // we would be reference-compatible or reference-compatible with
1917 // added qualification. But that wasn't the case, so the reference
1918 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001919 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001920 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001921 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001922 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1923 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001924 return true;
1925 }
1926
1927 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001928 if (ICS) {
1929 /// C++ [over.ics.ref]p2:
1930 ///
1931 /// When a parameter of reference type is not bound directly to
1932 /// an argument expression, the conversion sequence is the one
1933 /// required to convert the argument expression to the
1934 /// underlying type of the reference according to
1935 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1936 /// to copy-initializing a temporary of the underlying type with
1937 /// the argument expression. Any difference in top-level
1938 /// cv-qualification is subsumed by the initialization itself
1939 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001940 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001941 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1942 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00001943 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00001944 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001945}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001946
1947/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1948/// of this overloaded operator is well-formed. If so, returns false;
1949/// otherwise, emits appropriate diagnostics and returns true.
1950bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001951 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001952 "Expected an overloaded operator declaration");
1953
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001954 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1955
1956 // C++ [over.oper]p5:
1957 // The allocation and deallocation functions, operator new,
1958 // operator new[], operator delete and operator delete[], are
1959 // described completely in 3.7.3. The attributes and restrictions
1960 // found in the rest of this subclause do not apply to them unless
1961 // explicitly stated in 3.7.3.
1962 // FIXME: Write a separate routine for checking this. For now, just
1963 // allow it.
1964 if (Op == OO_New || Op == OO_Array_New ||
1965 Op == OO_Delete || Op == OO_Array_Delete)
1966 return false;
1967
1968 // C++ [over.oper]p6:
1969 // An operator function shall either be a non-static member
1970 // function or be a non-member function and have at least one
1971 // parameter whose type is a class, a reference to a class, an
1972 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001973 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1974 if (MethodDecl->isStatic())
1975 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001976 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001977 } else {
1978 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001979 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1980 ParamEnd = FnDecl->param_end();
1981 Param != ParamEnd; ++Param) {
1982 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001983 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1984 ClassOrEnumParam = true;
1985 break;
1986 }
1987 }
1988
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001989 if (!ClassOrEnumParam)
1990 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001991 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001992 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001993 }
1994
1995 // C++ [over.oper]p8:
1996 // An operator function cannot have default arguments (8.3.6),
1997 // except where explicitly stated below.
1998 //
1999 // Only the function-call operator allows default arguments
2000 // (C++ [over.call]p1).
2001 if (Op != OO_Call) {
2002 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2003 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002004 if ((*Param)->hasUnparsedDefaultArg())
2005 return Diag((*Param)->getLocation(),
2006 diag::err_operator_overload_default_arg)
2007 << FnDecl->getDeclName();
2008 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002009 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002010 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002011 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002012 }
2013 }
2014
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002015 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2016 { false, false, false }
2017#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2018 , { Unary, Binary, MemberOnly }
2019#include "clang/Basic/OperatorKinds.def"
2020 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002021
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002022 bool CanBeUnaryOperator = OperatorUses[Op][0];
2023 bool CanBeBinaryOperator = OperatorUses[Op][1];
2024 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002025
2026 // C++ [over.oper]p8:
2027 // [...] Operator functions cannot have more or fewer parameters
2028 // than the number required for the corresponding operator, as
2029 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002030 unsigned NumParams = FnDecl->getNumParams()
2031 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002032 if (Op != OO_Call &&
2033 ((NumParams == 1 && !CanBeUnaryOperator) ||
2034 (NumParams == 2 && !CanBeBinaryOperator) ||
2035 (NumParams < 1) || (NumParams > 2))) {
2036 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002037 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002038 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002039 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002040 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002041 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002042 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002043 assert(CanBeBinaryOperator &&
2044 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002045 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002046 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002047
Chris Lattner416e46f2008-11-21 07:57:12 +00002048 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002049 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002050 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002051
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002052 // Overloaded operators other than operator() cannot be variadic.
2053 if (Op != OO_Call &&
2054 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002055 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002056 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002057 }
2058
2059 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002060 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2061 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002062 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002063 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002064 }
2065
2066 // C++ [over.inc]p1:
2067 // The user-defined function called operator++ implements the
2068 // prefix and postfix ++ operator. If this function is a member
2069 // function with no parameters, or a non-member function with one
2070 // parameter of class or enumeration type, it defines the prefix
2071 // increment operator ++ for objects of that type. If the function
2072 // is a member function with one parameter (which shall be of type
2073 // int) or a non-member function with two parameters (the second
2074 // of which shall be of type int), it defines the postfix
2075 // increment operator ++ for objects of that type.
2076 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2077 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2078 bool ParamIsInt = false;
2079 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2080 ParamIsInt = BT->getKind() == BuiltinType::Int;
2081
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002082 if (!ParamIsInt)
2083 return Diag(LastParam->getLocation(),
2084 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002085 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002086 }
2087
Sebastian Redl64b45f72009-01-05 20:52:13 +00002088 // Notify the class if it got an assignment operator.
2089 if (Op == OO_Equal) {
2090 // Would have returned earlier otherwise.
2091 assert(isa<CXXMethodDecl>(FnDecl) &&
2092 "Overloaded = not member, but not filtered.");
2093 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2094 Method->getParent()->addedAssignmentOperator(Context, Method);
2095 }
2096
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002097 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002098}
Chris Lattner5a003a42008-12-17 07:09:26 +00002099
Douglas Gregor074149e2009-01-05 19:45:36 +00002100/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2101/// linkage specification, including the language and (if present)
2102/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2103/// the location of the language string literal, which is provided
2104/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2105/// the '{' brace. Otherwise, this linkage specification does not
2106/// have any braces.
2107Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2108 SourceLocation ExternLoc,
2109 SourceLocation LangLoc,
2110 const char *Lang,
2111 unsigned StrSize,
2112 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002113 LinkageSpecDecl::LanguageIDs Language;
2114 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2115 Language = LinkageSpecDecl::lang_c;
2116 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2117 Language = LinkageSpecDecl::lang_cxx;
2118 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002119 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002120 return 0;
2121 }
2122
2123 // FIXME: Add all the various semantics of linkage specifications
2124
Douglas Gregor074149e2009-01-05 19:45:36 +00002125 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2126 LangLoc, Language,
2127 LBraceLoc.isValid());
2128 CurContext->addDecl(Context, D);
2129 PushDeclContext(S, D);
2130 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002131}
2132
Douglas Gregor074149e2009-01-05 19:45:36 +00002133/// ActOnFinishLinkageSpecification - Completely the definition of
2134/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2135/// valid, it's the position of the closing '}' brace in a linkage
2136/// specification that uses braces.
2137Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2138 DeclTy *LinkageSpec,
2139 SourceLocation RBraceLoc) {
2140 if (LinkageSpec)
2141 PopDeclContext();
2142 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002143}
2144
Sebastian Redl4b07b292008-12-22 19:15:10 +00002145/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2146/// handler.
2147Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2148{
2149 QualType ExDeclType = GetTypeForDeclarator(D, S);
2150 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2151
2152 bool Invalid = false;
2153
2154 // Arrays and functions decay.
2155 if (ExDeclType->isArrayType())
2156 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2157 else if (ExDeclType->isFunctionType())
2158 ExDeclType = Context.getPointerType(ExDeclType);
2159
2160 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2161 // The exception-declaration shall not denote a pointer or reference to an
2162 // incomplete type, other than [cv] void*.
2163 QualType BaseType = ExDeclType;
2164 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2165 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2166 BaseType = Ptr->getPointeeType();
2167 Mode = 1;
2168 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2169 BaseType = Ref->getPointeeType();
2170 Mode = 2;
2171 }
2172 if ((Mode == 0 || !BaseType->isVoidType()) && BaseType->isIncompleteType()) {
2173 Invalid = true;
2174 Diag(Begin, diag::err_catch_incomplete) << BaseType << Mode;
2175 }
2176
Sebastian Redl8351da02008-12-22 21:35:02 +00002177 // FIXME: Need to test for ability to copy-construct and destroy the
2178 // exception variable.
2179 // FIXME: Need to check for abstract classes.
2180
Sebastian Redl4b07b292008-12-22 19:15:10 +00002181 IdentifierInfo *II = D.getIdentifier();
2182 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
2183 // The scope should be freshly made just for us. There is just no way
2184 // it contains any previous declaration.
2185 assert(!S->isDeclScope(PrevDecl));
2186 if (PrevDecl->isTemplateParameter()) {
2187 // Maybe we will complain about the shadowed template parameter.
2188 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2189
2190 }
2191 }
2192
2193 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2194 II, ExDeclType, VarDecl::None, 0, Begin);
2195 if (D.getInvalidType() || Invalid)
2196 ExDecl->setInvalidDecl();
2197
2198 if (D.getCXXScopeSpec().isSet()) {
2199 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2200 << D.getCXXScopeSpec().getRange();
2201 ExDecl->setInvalidDecl();
2202 }
2203
2204 // Add the exception declaration into this scope.
2205 S->AddDecl(ExDecl);
2206 if (II)
2207 IdResolver.AddDecl(ExDecl);
2208
2209 ProcessDeclAttributes(ExDecl, D);
2210 return ExDecl;
2211}