blob: 7be76bba1a02b6052d501159069733922f21c229 [file] [log] [blame]
Chris Lattnerac7b83a2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000128 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
129 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000130 if (DefaultArgPtr != DefaultArg.get()) {
131 DefaultArg.take();
132 DefaultArg.reset(DefaultArgPtr);
133 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000134 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000135 return;
136 }
137
Chris Lattner97316c02008-04-10 02:22:51 +0000138 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000139 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000140 if (DefaultArgChecker.Visit(DefaultArg.get())) {
141 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000142 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000143 }
Chris Lattner97316c02008-04-10 02:22:51 +0000144
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000145 // Okay: add the default argument to the parameter
146 Param->setDefaultArg(DefaultArg.take());
147}
148
Douglas Gregor605de8d2008-12-16 21:30:33 +0000149/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
150/// the default argument for the parameter param failed.
151void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
152 ((ParmVarDecl*)param)->setInvalidDecl();
153}
154
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000155/// CheckExtraCXXDefaultArguments - Check for any extra default
156/// arguments in the declarator, which is not a function declaration
157/// or definition and therefore is not permitted to have default
158/// arguments. This routine should be invoked for every declarator
159/// that is not a function declaration or definition.
160void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
161 // C++ [dcl.fct.default]p3
162 // A default argument expression shall be specified only in the
163 // parameter-declaration-clause of a function declaration or in a
164 // template-parameter (14.1). It shall not be specified for a
165 // parameter pack. If it is specified in a
166 // parameter-declaration-clause, it shall not occur within a
167 // declarator or abstract-declarator of a parameter-declaration.
168 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
169 DeclaratorChunk &chunk = D.getTypeObject(i);
170 if (chunk.Kind == DeclaratorChunk::Function) {
171 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
172 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
173 if (Param->getDefaultArg()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000174 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
175 << Param->getDefaultArg()->getSourceRange();
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000176 Param->setDefaultArg(0);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000177 } else if (CachedTokens *Toks
178 = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens) {
179 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
180 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
181 delete Toks;
182 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000183 }
184 }
185 }
186 }
187}
188
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000189// MergeCXXFunctionDecl - Merge two declarations of the same C++
190// function, once we already know that they have the same
191// type. Subroutine of MergeFunctionDecl.
192FunctionDecl *
193Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
194 // C++ [dcl.fct.default]p4:
195 //
196 // For non-template functions, default arguments can be added in
197 // later declarations of a function in the same
198 // scope. Declarations in different scopes have completely
199 // distinct sets of default arguments. That is, declarations in
200 // inner scopes do not acquire default arguments from
201 // declarations in outer scopes, and vice versa. In a given
202 // function declaration, all parameters subsequent to a
203 // parameter with a default argument shall have default
204 // arguments supplied in this or previous declarations. A
205 // default argument shall not be redefined by a later
206 // declaration (not even to the same value).
207 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
208 ParmVarDecl *OldParam = Old->getParamDecl(p);
209 ParmVarDecl *NewParam = New->getParamDecl(p);
210
211 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
212 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000213 diag::err_param_default_argument_redefinition)
214 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000215 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000216 } else if (OldParam->getDefaultArg()) {
217 // Merge the old default argument into the new parameter
218 NewParam->setDefaultArg(OldParam->getDefaultArg());
219 }
220 }
221
222 return New;
223}
224
225/// CheckCXXDefaultArguments - Verify that the default arguments for a
226/// function declaration are well-formed according to C++
227/// [dcl.fct.default].
228void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
229 unsigned NumParams = FD->getNumParams();
230 unsigned p;
231
232 // Find first parameter with a default argument
233 for (p = 0; p < NumParams; ++p) {
234 ParmVarDecl *Param = FD->getParamDecl(p);
235 if (Param->getDefaultArg())
236 break;
237 }
238
239 // C++ [dcl.fct.default]p4:
240 // In a given function declaration, all parameters
241 // subsequent to a parameter with a default argument shall
242 // have default arguments supplied in this or previous
243 // declarations. A default argument shall not be redefined
244 // by a later declaration (not even to the same value).
245 unsigned LastMissingDefaultArg = 0;
246 for(; p < NumParams; ++p) {
247 ParmVarDecl *Param = FD->getParamDecl(p);
248 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000249 if (Param->isInvalidDecl())
250 /* We already complained about this parameter. */;
251 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000252 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000253 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000254 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000255 else
256 Diag(Param->getLocation(),
257 diag::err_param_default_argument_missing);
258
259 LastMissingDefaultArg = p;
260 }
261 }
262
263 if (LastMissingDefaultArg > 0) {
264 // Some default arguments were missing. Clear out all of the
265 // default arguments up to (and including) the last missing
266 // default argument, so that we leave the function parameters
267 // in a semantically valid state.
268 for (p = 0; p <= LastMissingDefaultArg; ++p) {
269 ParmVarDecl *Param = FD->getParamDecl(p);
270 if (Param->getDefaultArg()) {
271 delete Param->getDefaultArg();
272 Param->setDefaultArg(0);
273 }
274 }
275 }
276}
Douglas Gregorec93f442008-04-13 21:30:24 +0000277
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000278/// isCurrentClassName - Determine whether the identifier II is the
279/// name of the class type currently being defined. In the case of
280/// nested classes, this will only return true if II is the name of
281/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000282bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
283 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000284 CXXRecordDecl *CurDecl;
285 if (SS) {
286 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
287 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
288 } else
289 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
290
291 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000292 return &II == CurDecl->getIdentifier();
293 else
294 return false;
295}
296
Douglas Gregorec93f442008-04-13 21:30:24 +0000297/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
298/// one entry in the base class list of a class specifier, for
299/// example:
300/// class foo : public bar, virtual private baz {
301/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000302Sema::BaseResult
303Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
304 bool Virtual, AccessSpecifier Access,
305 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000306 RecordDecl *Decl = (RecordDecl*)classdecl;
307 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
308
309 // Base specifiers must be record types.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000310 if (!BaseType->isRecordType())
311 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000312
313 // C++ [class.union]p1:
314 // A union shall not be used as a base class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000315 if (BaseType->isUnionType())
316 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000317
318 // C++ [class.union]p1:
319 // A union shall not have base classes.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000320 if (Decl->isUnion())
321 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
322 << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000323
324 // C++ [class.derived]p2:
325 // The class-name in a base-specifier shall not be an incompletely
326 // defined class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000327 if (BaseType->isIncompleteType())
328 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000329
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000330 // If the base class is polymorphic, the new one is, too.
331 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
332 assert(BaseDecl && "Record type has no declaration");
333 BaseDecl = BaseDecl->getDefinition(Context);
334 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattner8ba580c2008-11-19 05:08:23 +0000335 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000336 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000337
Douglas Gregorabed2172008-10-22 17:49:05 +0000338 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000339 return new CXXBaseSpecifier(SpecifierRange, Virtual,
340 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000341}
Douglas Gregorec93f442008-04-13 21:30:24 +0000342
Douglas Gregorabed2172008-10-22 17:49:05 +0000343/// ActOnBaseSpecifiers - Attach the given base specifiers to the
344/// class, after checking whether there are any duplicate base
345/// classes.
346void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
347 unsigned NumBases) {
348 if (NumBases == 0)
349 return;
350
351 // Used to keep track of which base types we have already seen, so
352 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000353 // that the key is always the unqualified canonical type of the base
354 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000355 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
356
357 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000358 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
359 unsigned NumGoodBases = 0;
360 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000361 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000362 = Context.getCanonicalType(BaseSpecs[idx]->getType());
363 NewBaseType = NewBaseType.getUnqualifiedType();
364
Douglas Gregorabed2172008-10-22 17:49:05 +0000365 if (KnownBaseTypes[NewBaseType]) {
366 // C++ [class.mi]p3:
367 // A class shall not be specified as a direct base class of a
368 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000369 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000370 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000371 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000372 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000373
374 // Delete the duplicate base class specifier; we're going to
375 // overwrite its pointer later.
376 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000377 } else {
378 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000379 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
380 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000381 }
382 }
383
384 // Attach the remaining base class specifiers to the derived class.
385 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000386 Decl->setBases(BaseSpecs, NumGoodBases);
387
388 // Delete the remaining (good) base class specifiers, since their
389 // data has been copied into the CXXRecordDecl.
390 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
391 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000392}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000393
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000394//===----------------------------------------------------------------------===//
395// C++ class member Handling
396//===----------------------------------------------------------------------===//
397
398/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
399/// definition, when on C++.
400void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000401 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Douglas Gregor8acb7272008-12-11 16:49:14 +0000402 PushDeclContext(S, Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000403 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000404
405 if (Dcl->getIdentifier()) {
406 // C++ [class]p2:
407 // [...] The class-name is also inserted into the scope of the
408 // class itself; this is known as the injected-class-name. For
409 // purposes of access checking, the injected-class-name is treated
410 // as if it were a public member name.
Douglas Gregor4b00d562008-12-17 16:48:01 +0000411 PushOnScopeChains(CXXRecordDecl::Create(Context, Dcl->getTagKind(),
412 CurContext, Dcl->getLocation(),
413 Dcl->getIdentifier(), Dcl), S);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000414 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000415}
416
417/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
418/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
419/// bitfield width if there is one and 'InitExpr' specifies the initializer if
420/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
421/// declarators on it.
422///
Douglas Gregor605de8d2008-12-16 21:30:33 +0000423/// FIXME: The note below is out-of-date.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000424/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
425/// an instance field is declared, a new CXXFieldDecl is created but the method
426/// does *not* return it; it returns LastInGroup instead. The other C++ members
427/// (which are all ScopedDecls) are returned after appending them to
428/// LastInGroup.
429Sema::DeclTy *
430Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
431 ExprTy *BW, ExprTy *InitExpr,
432 DeclTy *LastInGroup) {
433 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000434 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000435 Expr *BitWidth = static_cast<Expr*>(BW);
436 Expr *Init = static_cast<Expr*>(InitExpr);
437 SourceLocation Loc = D.getIdentifierLoc();
438
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000439 bool isFunc = D.isFunctionDeclarator();
440
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000441 // C++ 9.2p6: A member shall not be declared to have automatic storage
442 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000443 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
444 // data members and cannot be applied to names declared const or static,
445 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000446 switch (DS.getStorageClassSpec()) {
447 case DeclSpec::SCS_unspecified:
448 case DeclSpec::SCS_typedef:
449 case DeclSpec::SCS_static:
450 // FALL THROUGH.
451 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000452 case DeclSpec::SCS_mutable:
453 if (isFunc) {
454 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000455 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000456 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000457 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
458
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000459 // FIXME: It would be nicer if the keyword was ignored only for this
460 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000461 D.getMutableDeclSpec().ClearStorageClassSpecs();
462 } else {
463 QualType T = GetTypeForDeclarator(D, S);
464 diag::kind err = static_cast<diag::kind>(0);
465 if (T->isReferenceType())
466 err = diag::err_mutable_reference;
467 else if (T.isConstQualified())
468 err = diag::err_mutable_const;
469 if (err != 0) {
470 if (DS.getStorageClassSpecLoc().isValid())
471 Diag(DS.getStorageClassSpecLoc(), err);
472 else
473 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000474 // FIXME: It would be nicer if the keyword was ignored only for this
475 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000476 D.getMutableDeclSpec().ClearStorageClassSpecs();
477 }
478 }
479 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000480 default:
481 if (DS.getStorageClassSpecLoc().isValid())
482 Diag(DS.getStorageClassSpecLoc(),
483 diag::err_storageclass_invalid_for_member);
484 else
485 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
486 D.getMutableDeclSpec().ClearStorageClassSpecs();
487 }
488
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000489 if (!isFunc &&
490 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
491 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000492 // Check also for this case:
493 //
494 // typedef int f();
495 // f a;
496 //
497 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
498 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
499 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000500
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000501 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
502 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000503 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000504
505 Decl *Member;
506 bool InvalidDecl = false;
507
508 if (isInstField)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000509 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
510 Loc, D, BitWidth));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000511 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000512 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000513
514 if (!Member) return LastInGroup;
515
Douglas Gregor6704b312008-11-17 22:58:34 +0000516 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000517
518 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
519 // specific methods. Use a wrapper class that can be used with all C++ class
520 // member decls.
521 CXXClassMemberWrapper(Member).setAccess(AS);
522
Douglas Gregor15e04622008-11-05 16:20:31 +0000523 // C++ [dcl.init.aggr]p1:
524 // An aggregate is an array or a class (clause 9) with [...] no
525 // private or protected non-static data members (clause 11).
526 if (isInstField && (AS == AS_private || AS == AS_protected))
527 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
528
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000529 if (DS.isVirtualSpecified()) {
530 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
531 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
532 InvalidDecl = true;
533 } else {
534 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
535 CurClass->setAggregate(false);
536 CurClass->setPolymorphic(true);
537 }
538 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000539
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000540 if (BitWidth) {
541 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
542 // constant-expression be a value equal to zero.
543 // FIXME: Check this.
544
545 if (D.isFunctionDeclarator()) {
546 // FIXME: Emit diagnostic about only constructors taking base initializers
547 // or something similar, when constructor support is in place.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000548 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000549 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000550 InvalidDecl = true;
551
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000552 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000553 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000554 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000555 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000556 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000557 InvalidDecl = true;
558 }
559
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000560 } else if (isa<FunctionDecl>(Member)) {
561 // A function typedef ("typedef int f(); f a;").
562 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000563 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000564 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000565 InvalidDecl = true;
566
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000567 } else if (isa<TypedefDecl>(Member)) {
568 // "cannot declare 'A' to be a bit-field type"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000569 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000570 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000571 InvalidDecl = true;
572
573 } else {
574 assert(isa<CXXClassVarDecl>(Member) &&
575 "Didn't we cover all member kinds?");
576 // C++ 9.6p3: A bit-field shall not be a static member.
577 // "static member 'A' cannot be a bit-field"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000578 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000579 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000580 InvalidDecl = true;
581 }
582 }
583
584 if (Init) {
585 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
586 // if it declares a static member of const integral or const enumeration
587 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000588 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
589 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000590 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000591 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000592 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
593 CVD->getType()->isIntegralType()) {
594 // constant-initializer
595 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000596 InvalidDecl = true;
597
598 } else {
599 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000600 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000601 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000602 InvalidDecl = true;
603 }
604
605 } else {
606 // not static member.
Chris Lattner77d52da2008-11-20 06:06:08 +0000607 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000608 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000609 InvalidDecl = true;
610 }
611 }
612
613 if (InvalidDecl)
614 Member->setInvalidDecl();
615
616 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000617 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000618 return LastInGroup;
619 }
620 return Member;
621}
622
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000623/// ActOnMemInitializer - Handle a C++ member initializer.
624Sema::MemInitResult
625Sema::ActOnMemInitializer(DeclTy *ConstructorD,
626 Scope *S,
627 IdentifierInfo *MemberOrBase,
628 SourceLocation IdLoc,
629 SourceLocation LParenLoc,
630 ExprTy **Args, unsigned NumArgs,
631 SourceLocation *CommaLocs,
632 SourceLocation RParenLoc) {
633 CXXConstructorDecl *Constructor
634 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
635 if (!Constructor) {
636 // The user wrote a constructor initializer on a function that is
637 // not a C++ constructor. Ignore the error for now, because we may
638 // have more member initializers coming; we'll diagnose it just
639 // once in ActOnMemInitializers.
640 return true;
641 }
642
643 CXXRecordDecl *ClassDecl = Constructor->getParent();
644
645 // C++ [class.base.init]p2:
646 // Names in a mem-initializer-id are looked up in the scope of the
647 // constructor’s class and, if not found in that scope, are looked
648 // up in the scope containing the constructor’s
649 // definition. [Note: if the constructor’s class contains a member
650 // with the same name as a direct or virtual base class of the
651 // class, a mem-initializer-id naming the member or base class and
652 // composed of a single identifier refers to the class member. A
653 // mem-initializer-id for the hidden base class may be specified
654 // using a qualified name. ]
655 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000656 FieldDecl *Member = 0;
657 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase);
658 if (Result.first != Result.second)
659 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000660
661 // FIXME: Handle members of an anonymous union.
662
663 if (Member) {
664 // FIXME: Perform direct initialization of the member.
665 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
666 }
667
668 // It didn't name a member, so see if it names a class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000669 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000670 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000671 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
672 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000673
674 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
675 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000676 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000677 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000678
679 // C++ [class.base.init]p2:
680 // [...] Unless the mem-initializer-id names a nonstatic data
681 // member of the constructor’s class or a direct or virtual base
682 // of that class, the mem-initializer is ill-formed. A
683 // mem-initializer-list can initialize a base class using any
684 // name that denotes that base class type.
685
686 // First, check for a direct base class.
687 const CXXBaseSpecifier *DirectBaseSpec = 0;
688 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
689 Base != ClassDecl->bases_end(); ++Base) {
690 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
691 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
692 // We found a direct base of this type. That's what we're
693 // initializing.
694 DirectBaseSpec = &*Base;
695 break;
696 }
697 }
698
699 // Check for a virtual base class.
700 // FIXME: We might be able to short-circuit this if we know in
701 // advance that there are no virtual bases.
702 const CXXBaseSpecifier *VirtualBaseSpec = 0;
703 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
704 // We haven't found a base yet; search the class hierarchy for a
705 // virtual base class.
706 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
707 /*DetectVirtual=*/false);
708 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
709 for (BasePaths::paths_iterator Path = Paths.begin();
710 Path != Paths.end(); ++Path) {
711 if (Path->back().Base->isVirtual()) {
712 VirtualBaseSpec = Path->back().Base;
713 break;
714 }
715 }
716 }
717 }
718
719 // C++ [base.class.init]p2:
720 // If a mem-initializer-id is ambiguous because it designates both
721 // a direct non-virtual base class and an inherited virtual base
722 // class, the mem-initializer is ill-formed.
723 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000724 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
725 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000726
727 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
728}
729
730
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000731void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
732 DeclTy *TagDecl,
733 SourceLocation LBrac,
734 SourceLocation RBrac) {
735 ActOnFields(S, RLoc, TagDecl,
736 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000737 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000738}
739
Douglas Gregore640ab62008-11-03 17:51:48 +0000740/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
741/// special functions, such as the default constructor, copy
742/// constructor, or destructor, to the given C++ class (C++
743/// [special]p1). This routine can only be executed just before the
744/// definition of the class is complete.
745void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000746 QualType ClassType = Context.getTypeDeclType(ClassDecl);
747 ClassType = Context.getCanonicalType(ClassType);
748
Douglas Gregore640ab62008-11-03 17:51:48 +0000749 if (!ClassDecl->hasUserDeclaredConstructor()) {
750 // C++ [class.ctor]p5:
751 // A default constructor for a class X is a constructor of class X
752 // that can be called without an argument. If there is no
753 // user-declared constructor for class X, a default constructor is
754 // implicitly declared. An implicitly-declared default constructor
755 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000756 DeclarationName Name
757 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000758 CXXConstructorDecl *DefaultCon =
759 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000760 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000761 Context.getFunctionType(Context.VoidTy,
762 0, 0, false, 0),
763 /*isExplicit=*/false,
764 /*isInline=*/true,
765 /*isImplicitlyDeclared=*/true);
766 DefaultCon->setAccess(AS_public);
Douglas Gregorb9213832008-12-15 21:24:18 +0000767 ClassDecl->addDecl(Context, DefaultCon);
768
769 // Notify the class that we've added a constructor.
770 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000771 }
772
773 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
774 // C++ [class.copy]p4:
775 // If the class definition does not explicitly declare a copy
776 // constructor, one is declared implicitly.
777
778 // C++ [class.copy]p5:
779 // The implicitly-declared copy constructor for a class X will
780 // have the form
781 //
782 // X::X(const X&)
783 //
784 // if
785 bool HasConstCopyConstructor = true;
786
787 // -- each direct or virtual base class B of X has a copy
788 // constructor whose first parameter is of type const B& or
789 // const volatile B&, and
790 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
791 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
792 const CXXRecordDecl *BaseClassDecl
793 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
794 HasConstCopyConstructor
795 = BaseClassDecl->hasConstCopyConstructor(Context);
796 }
797
798 // -- for all the nonstatic data members of X that are of a
799 // class type M (or array thereof), each such class type
800 // has a copy constructor whose first parameter is of type
801 // const M& or const volatile M&.
802 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
803 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
804 QualType FieldType = (*Field)->getType();
805 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
806 FieldType = Array->getElementType();
807 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
808 const CXXRecordDecl *FieldClassDecl
809 = cast<CXXRecordDecl>(FieldClassType->getDecl());
810 HasConstCopyConstructor
811 = FieldClassDecl->hasConstCopyConstructor(Context);
812 }
813 }
814
815 // Otherwise, the implicitly declared copy constructor will have
816 // the form
817 //
818 // X::X(X&)
819 QualType ArgType = Context.getTypeDeclType(ClassDecl);
820 if (HasConstCopyConstructor)
821 ArgType = ArgType.withConst();
822 ArgType = Context.getReferenceType(ArgType);
823
824 // An implicitly-declared copy constructor is an inline public
825 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000826 DeclarationName Name
827 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000828 CXXConstructorDecl *CopyConstructor
829 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000830 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000831 Context.getFunctionType(Context.VoidTy,
832 &ArgType, 1,
833 false, 0),
834 /*isExplicit=*/false,
835 /*isInline=*/true,
836 /*isImplicitlyDeclared=*/true);
837 CopyConstructor->setAccess(AS_public);
838
839 // Add the parameter to the constructor.
840 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
841 ClassDecl->getLocation(),
842 /*IdentifierInfo=*/0,
843 ArgType, VarDecl::None, 0, 0);
844 CopyConstructor->setParams(&FromParam, 1);
845
Douglas Gregorb9213832008-12-15 21:24:18 +0000846 ClassDecl->addedConstructor(Context, CopyConstructor);
847 DeclContext::lookup_result Lookup = ClassDecl->lookup(Context, Name);
848 if (Lookup.first == Lookup.second
849 || (!isa<CXXConstructorDecl>(*Lookup.first) &&
850 !isa<OverloadedFunctionDecl>(*Lookup.first)))
851 ClassDecl->addDecl(Context, CopyConstructor);
852 else {
853 OverloadedFunctionDecl *Ovl
854 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first);
855 if (!Ovl) {
856 Ovl = OverloadedFunctionDecl::Create(Context, ClassDecl, Name);
857 Ovl->addOverload(cast<CXXConstructorDecl>(*Lookup.first));
858 ClassDecl->insert(Context, Ovl);
859 }
860
861 Ovl->addOverload(CopyConstructor);
862 ClassDecl->addDecl(Context, CopyConstructor, false);
863 }
Douglas Gregore640ab62008-11-03 17:51:48 +0000864 }
865
Douglas Gregorb9213832008-12-15 21:24:18 +0000866 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000867 // C++ [class.dtor]p2:
868 // If a class has no user-declared destructor, a destructor is
869 // declared implicitly. An implicitly-declared destructor is an
870 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000871 DeclarationName Name
872 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000873 CXXDestructorDecl *Destructor
874 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000875 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000876 Context.getFunctionType(Context.VoidTy,
877 0, 0, false, 0),
878 /*isInline=*/true,
879 /*isImplicitlyDeclared=*/true);
880 Destructor->setAccess(AS_public);
Douglas Gregorb9213832008-12-15 21:24:18 +0000881 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000882 }
883
Douglas Gregore640ab62008-11-03 17:51:48 +0000884 // FIXME: Implicit copy assignment operator
885}
886
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000887void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000888 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000889 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000890 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000891 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000892
893 // Everything, including inline method definitions, have been parsed.
894 // Let the consumer know of the new TagDecl definition.
895 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000896}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000897
Douglas Gregor605de8d2008-12-16 21:30:33 +0000898/// ActOnStartDelayedCXXMethodDeclaration - We have completed
899/// parsing a top-level (non-nested) C++ class, and we are now
900/// parsing those parts of the given Method declaration that could
901/// not be parsed earlier (C++ [class.mem]p2), such as default
902/// arguments. This action should enter the scope of the given
903/// Method declaration as if we had just parsed the qualified method
904/// name. However, it should not bring the parameters into scope;
905/// that will be performed by ActOnDelayedCXXMethodParameter.
906void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
907 CXXScopeSpec SS;
908 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
909 ActOnCXXEnterDeclaratorScope(S, SS);
910}
911
912/// ActOnDelayedCXXMethodParameter - We've already started a delayed
913/// C++ method declaration. We're (re-)introducing the given
914/// function parameter into scope for use in parsing later parts of
915/// the method declaration. For example, we could see an
916/// ActOnParamDefaultArgument event for this parameter.
917void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
918 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
919 S->AddDecl(Param);
920 if (Param->getDeclName())
921 IdResolver.AddDecl(Param);
922}
923
924/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
925/// processing the delayed method declaration for Method. The method
926/// declaration is now considered finished. There may be a separate
927/// ActOnStartOfFunctionDef action later (not necessarily
928/// immediately!) for this method, if it was also defined inside the
929/// class body.
930void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
931 FunctionDecl *Method = (FunctionDecl*)MethodD;
932 CXXScopeSpec SS;
933 SS.setScopeRep(Method->getDeclContext());
934 ActOnCXXExitDeclaratorScope(S, SS);
935
936 // Now that we have our default arguments, check the constructor
937 // again. It could produce additional diagnostics or affect whether
938 // the class has implicitly-declared destructors, among other
939 // things.
940 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
941 if (CheckConstructor(Constructor))
942 Constructor->setInvalidDecl();
943 }
944
945 // Check the default arguments, which we may have added.
946 if (!Method->isInvalidDecl())
947 CheckCXXDefaultArguments(Method);
948}
949
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000950/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +0000951/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000952/// R. If there are any errors in the declarator, this routine will
953/// emit diagnostics and return true. Otherwise, it will return
954/// false. Either way, the type @p R will be updated to reflect a
955/// well-formed type for the constructor.
956bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
957 FunctionDecl::StorageClass& SC) {
958 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
959 bool isInvalid = false;
960
961 // C++ [class.ctor]p3:
962 // A constructor shall not be virtual (10.3) or static (9.4). A
963 // constructor can be invoked for a const, volatile or const
964 // volatile object. A constructor shall not be declared const,
965 // volatile, or const volatile (9.3.2).
966 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000967 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
968 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
969 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000970 isInvalid = true;
971 }
972 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000973 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
974 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
975 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000976 isInvalid = true;
977 SC = FunctionDecl::None;
978 }
979 if (D.getDeclSpec().hasTypeSpecifier()) {
980 // Constructors don't have return types, but the parser will
981 // happily parse something like:
982 //
983 // class X {
984 // float X(float);
985 // };
986 //
987 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000988 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
989 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
990 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000991 }
992 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
993 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
994 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
996 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000997 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
999 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001000 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001001 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1002 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001003 }
1004
1005 // Rebuild the function type "R" without any type qualifiers (in
1006 // case any of the errors above fired) and with "void" as the
1007 // return type, since constructors don't have return types. We
1008 // *always* have to do this, because GetTypeForDeclarator will
1009 // put in a result type of "int" when none was specified.
1010 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1011 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1012 Proto->getNumArgs(),
1013 Proto->isVariadic(),
1014 0);
1015
1016 return isInvalid;
1017}
1018
Douglas Gregor605de8d2008-12-16 21:30:33 +00001019/// CheckConstructor - Checks a fully-formed constructor for
1020/// well-formedness, issuing any diagnostics required. Returns true if
1021/// the constructor declarator is invalid.
1022bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1023 if (Constructor->isInvalidDecl())
1024 return true;
1025
1026 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1027 bool Invalid = false;
1028
1029 // C++ [class.copy]p3:
1030 // A declaration of a constructor for a class X is ill-formed if
1031 // its first parameter is of type (optionally cv-qualified) X and
1032 // either there are no other parameters or else all other
1033 // parameters have default arguments.
1034 if ((Constructor->getNumParams() == 1) ||
1035 (Constructor->getNumParams() > 1 &&
1036 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1037 QualType ParamType = Constructor->getParamDecl(0)->getType();
1038 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1039 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1040 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1041 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1042 Invalid = true;
1043 }
1044 }
1045
1046 // Notify the class that we've added a constructor.
1047 ClassDecl->addedConstructor(Context, Constructor);
1048
1049 return Invalid;
1050}
1051
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001052/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1053/// the well-formednes of the destructor declarator @p D with type @p
1054/// R. If there are any errors in the declarator, this routine will
1055/// emit diagnostics and return true. Otherwise, it will return
1056/// false. Either way, the type @p R will be updated to reflect a
1057/// well-formed type for the destructor.
1058bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1059 FunctionDecl::StorageClass& SC) {
1060 bool isInvalid = false;
1061
1062 // C++ [class.dtor]p1:
1063 // [...] A typedef-name that names a class is a class-name
1064 // (7.1.3); however, a typedef-name that names a class shall not
1065 // be used as the identifier in the declarator for a destructor
1066 // declaration.
1067 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1068 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001069 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattner271d4c22008-11-24 05:29:24 +00001070 << TypedefD->getDeclName();
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001071 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001072 }
1073
1074 // C++ [class.dtor]p2:
1075 // A destructor is used to destroy objects of its class type. A
1076 // destructor takes no parameters, and no return type can be
1077 // specified for it (not even void). The address of a destructor
1078 // shall not be taken. A destructor shall not be static. A
1079 // destructor can be invoked for a const, volatile or const
1080 // volatile object. A destructor shall not be declared const,
1081 // volatile or const volatile (9.3.2).
1082 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1084 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1085 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001086 isInvalid = true;
1087 SC = FunctionDecl::None;
1088 }
1089 if (D.getDeclSpec().hasTypeSpecifier()) {
1090 // Destructors don't have return types, but the parser will
1091 // happily parse something like:
1092 //
1093 // class X {
1094 // float ~X();
1095 // };
1096 //
1097 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001098 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1099 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1100 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001101 }
1102 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1103 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1104 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001105 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1106 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001107 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1109 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001110 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1112 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001113 }
1114
1115 // Make sure we don't have any parameters.
1116 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1117 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1118
1119 // Delete the parameters.
1120 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1121 if (FTI.NumArgs) {
1122 delete [] FTI.ArgInfo;
1123 FTI.NumArgs = 0;
1124 FTI.ArgInfo = 0;
1125 }
1126 }
1127
1128 // Make sure the destructor isn't variadic.
1129 if (R->getAsFunctionTypeProto()->isVariadic())
1130 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1131
1132 // Rebuild the function type "R" without any type qualifiers or
1133 // parameters (in case any of the errors above fired) and with
1134 // "void" as the return type, since destructors don't have return
1135 // types. We *always* have to do this, because GetTypeForDeclarator
1136 // will put in a result type of "int" when none was specified.
1137 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1138
1139 return isInvalid;
1140}
1141
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001142/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1143/// well-formednes of the conversion function declarator @p D with
1144/// type @p R. If there are any errors in the declarator, this routine
1145/// will emit diagnostics and return true. Otherwise, it will return
1146/// false. Either way, the type @p R will be updated to reflect a
1147/// well-formed type for the conversion operator.
1148bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1149 FunctionDecl::StorageClass& SC) {
1150 bool isInvalid = false;
1151
1152 // C++ [class.conv.fct]p1:
1153 // Neither parameter types nor return type can be specified. The
1154 // type of a conversion function (8.3.5) is “function taking no
1155 // parameter returning conversion-type-id.”
1156 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001157 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1158 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1159 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001160 isInvalid = true;
1161 SC = FunctionDecl::None;
1162 }
1163 if (D.getDeclSpec().hasTypeSpecifier()) {
1164 // Conversion functions don't have return types, but the parser will
1165 // happily parse something like:
1166 //
1167 // class X {
1168 // float operator bool();
1169 // };
1170 //
1171 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001172 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1173 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1174 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001175 }
1176
1177 // Make sure we don't have any parameters.
1178 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1179 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1180
1181 // Delete the parameters.
1182 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1183 if (FTI.NumArgs) {
1184 delete [] FTI.ArgInfo;
1185 FTI.NumArgs = 0;
1186 FTI.ArgInfo = 0;
1187 }
1188 }
1189
1190 // Make sure the conversion function isn't variadic.
1191 if (R->getAsFunctionTypeProto()->isVariadic())
1192 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1193
1194 // C++ [class.conv.fct]p4:
1195 // The conversion-type-id shall not represent a function type nor
1196 // an array type.
1197 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1198 if (ConvType->isArrayType()) {
1199 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1200 ConvType = Context.getPointerType(ConvType);
1201 } else if (ConvType->isFunctionType()) {
1202 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1203 ConvType = Context.getPointerType(ConvType);
1204 }
1205
1206 // Rebuild the function type "R" without any parameters (in case any
1207 // of the errors above fired) and with the conversion type as the
1208 // return type.
1209 R = Context.getFunctionType(ConvType, 0, 0, false,
1210 R->getAsFunctionTypeProto()->getTypeQuals());
1211
1212 return isInvalid;
1213}
1214
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001215/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1216/// the declaration of the given C++ conversion function. This routine
1217/// is responsible for recording the conversion function in the C++
1218/// class, if possible.
1219Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1220 assert(Conversion && "Expected to receive a conversion function declaration");
1221
Douglas Gregor98341042008-12-12 08:25:50 +00001222 // Set the lexical context of this conversion function
1223 Conversion->setLexicalDeclContext(CurContext);
1224
1225 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001226
1227 // Make sure we aren't redeclaring the conversion function.
1228 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1229 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1230 for (OverloadedFunctionDecl::function_iterator Func
1231 = Conversions->function_begin();
1232 Func != Conversions->function_end(); ++Func) {
1233 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1234 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1235 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1236 Diag(OtherConv->getLocation(),
1237 OtherConv->isThisDeclarationADefinition()?
Chris Lattner1336cab2008-11-23 23:12:31 +00001238 diag::note_previous_definition
1239 : diag::note_previous_declaration);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001240 Conversion->setInvalidDecl();
1241 return (DeclTy *)Conversion;
1242 }
1243 }
1244
1245 // C++ [class.conv.fct]p1:
1246 // [...] A conversion function is never used to convert a
1247 // (possibly cv-qualified) object to the (possibly cv-qualified)
1248 // same object type (or a reference to it), to a (possibly
1249 // cv-qualified) base class of that type (or a reference to it),
1250 // or to (possibly cv-qualified) void.
1251 // FIXME: Suppress this warning if the conversion function ends up
1252 // being a virtual function that overrides a virtual function in a
1253 // base class.
1254 QualType ClassType
1255 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1256 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1257 ConvType = ConvTypeRef->getPointeeType();
1258 if (ConvType->isRecordType()) {
1259 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1260 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001261 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001262 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001263 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001264 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001265 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001266 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001267 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001268 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001269 }
1270
1271 ClassDecl->addConversionFunction(Context, Conversion);
1272
1273 return (DeclTy *)Conversion;
1274}
1275
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001276//===----------------------------------------------------------------------===//
1277// Namespace Handling
1278//===----------------------------------------------------------------------===//
1279
1280/// ActOnStartNamespaceDef - This is called at the start of a namespace
1281/// definition.
1282Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1283 SourceLocation IdentLoc,
1284 IdentifierInfo *II,
1285 SourceLocation LBrace) {
1286 NamespaceDecl *Namespc =
1287 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1288 Namespc->setLBracLoc(LBrace);
1289
1290 Scope *DeclRegionScope = NamespcScope->getParent();
1291
1292 if (II) {
1293 // C++ [namespace.def]p2:
1294 // The identifier in an original-namespace-definition shall not have been
1295 // previously defined in the declarative region in which the
1296 // original-namespace-definition appears. The identifier in an
1297 // original-namespace-definition is the name of the namespace. Subsequently
1298 // in that declarative region, it is treated as an original-namespace-name.
1299
1300 Decl *PrevDecl =
Douglas Gregor8acb7272008-12-11 16:49:14 +00001301 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1302 /*enableLazyBuiltinCreation=*/false,
1303 /*LookupInParent=*/false);
1304
1305 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1306 // This is an extended namespace definition.
1307 // Attach this namespace decl to the chain of extended namespace
1308 // definitions.
1309 OrigNS->setNextNamespace(Namespc);
1310 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001311
Douglas Gregor8acb7272008-12-11 16:49:14 +00001312 // Remove the previous declaration from the scope.
1313 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001314 IdResolver.RemoveDecl(OrigNS);
1315 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001316 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001317 } else if (PrevDecl) {
1318 // This is an invalid name redefinition.
1319 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1320 << Namespc->getDeclName();
1321 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1322 Namespc->setInvalidDecl();
1323 // Continue on to push Namespc as current DeclContext and return it.
1324 }
1325
1326 PushOnScopeChains(Namespc, DeclRegionScope);
1327 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001328 // FIXME: Handle anonymous namespaces
1329 }
1330
1331 // Although we could have an invalid decl (i.e. the namespace name is a
1332 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001333 // FIXME: We should be able to push Namespc here, so that the
1334 // each DeclContext for the namespace has the declarations
1335 // that showed up in that particular namespace definition.
1336 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001337 return Namespc;
1338}
1339
1340/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1341/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1342void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1343 Decl *Dcl = static_cast<Decl *>(D);
1344 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1345 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1346 Namespc->setRBracLoc(RBrace);
1347 PopDeclContext();
1348}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001349
1350
1351/// AddCXXDirectInitializerToDecl - This action is called immediately after
1352/// ActOnDeclarator, when a C++ direct initializer is present.
1353/// e.g: "int x(1);"
1354void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1355 ExprTy **ExprTys, unsigned NumExprs,
1356 SourceLocation *CommaLocs,
1357 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001358 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001359 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001360
1361 // If there is no declaration, there was an error parsing it. Just ignore
1362 // the initializer.
1363 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001364 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001365 delete static_cast<Expr *>(ExprTys[i]);
1366 return;
1367 }
1368
1369 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1370 if (!VDecl) {
1371 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1372 RealDecl->setInvalidDecl();
1373 return;
1374 }
1375
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001376 // We will treat direct-initialization as a copy-initialization:
1377 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001378 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1379 //
1380 // Clients that want to distinguish between the two forms, can check for
1381 // direct initializer using VarDecl::hasCXXDirectInitializer().
1382 // A major benefit is that clients that don't particularly care about which
1383 // exactly form was it (like the CodeGen) can handle both cases without
1384 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001385
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001386 // C++ 8.5p11:
1387 // The form of initialization (using parentheses or '=') is generally
1388 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001389 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001390 QualType DeclInitType = VDecl->getType();
1391 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1392 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001393
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001394 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001395 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001396 = PerformInitializationByConstructor(DeclInitType,
1397 (Expr **)ExprTys, NumExprs,
1398 VDecl->getLocation(),
1399 SourceRange(VDecl->getLocation(),
1400 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001401 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001402 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001403 if (!Constructor) {
1404 RealDecl->setInvalidDecl();
1405 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001406
1407 // Let clients know that initialization was done with a direct
1408 // initializer.
1409 VDecl->setCXXDirectInitializer(true);
1410
1411 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1412 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001413 return;
1414 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001415
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001416 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001417 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1418 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001419 RealDecl->setInvalidDecl();
1420 return;
1421 }
1422
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001423 // Let clients know that initialization was done with a direct initializer.
1424 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001425
1426 assert(NumExprs == 1 && "Expected 1 expression");
1427 // Set the init expression, handles conversions.
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00001428 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001429}
Douglas Gregor81c29152008-10-29 00:13:59 +00001430
Douglas Gregor6428e762008-11-05 15:29:30 +00001431/// PerformInitializationByConstructor - Perform initialization by
1432/// constructor (C++ [dcl.init]p14), which may occur as part of
1433/// direct-initialization or copy-initialization. We are initializing
1434/// an object of type @p ClassType with the given arguments @p
1435/// Args. @p Loc is the location in the source code where the
1436/// initializer occurs (e.g., a declaration, member initializer,
1437/// functional cast, etc.) while @p Range covers the whole
1438/// initialization. @p InitEntity is the entity being initialized,
1439/// which may by the name of a declaration or a type. @p Kind is the
1440/// kind of initialization we're performing, which affects whether
1441/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001442/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001443/// when the initialization fails, emits a diagnostic and returns
1444/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001445CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001446Sema::PerformInitializationByConstructor(QualType ClassType,
1447 Expr **Args, unsigned NumArgs,
1448 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001449 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001450 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001451 const RecordType *ClassRec = ClassType->getAsRecordType();
1452 assert(ClassRec && "Can only initialize a class type here");
1453
1454 // C++ [dcl.init]p14:
1455 //
1456 // If the initialization is direct-initialization, or if it is
1457 // copy-initialization where the cv-unqualified version of the
1458 // source type is the same class as, or a derived class of, the
1459 // class of the destination, constructors are considered. The
1460 // applicable constructors are enumerated (13.3.1.3), and the
1461 // best one is chosen through overload resolution (13.3). The
1462 // constructor so selected is called to initialize the object,
1463 // with the initializer expression(s) as its argument(s). If no
1464 // constructor applies, or the overload resolution is ambiguous,
1465 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001466 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1467 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001468
1469 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001470 DeclarationName ConstructorName
1471 = Context.DeclarationNames.getCXXConstructorName(
1472 Context.getCanonicalType(ClassType.getUnqualifiedType()));
1473 DeclContext::lookup_const_result Lookup
1474 = ClassDecl->lookup(Context, ConstructorName);
1475 if (Lookup.first == Lookup.second)
1476 /* No constructors */;
1477 else if (OverloadedFunctionDecl *Constructors
1478 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) {
1479 for (OverloadedFunctionDecl::function_iterator Con
1480 = Constructors->function_begin();
1481 Con != Constructors->function_end(); ++Con) {
1482 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1483 if ((Kind == IK_Direct) ||
1484 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1485 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1486 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1487 }
1488 } else if (CXXConstructorDecl *Constructor
1489 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001490 if ((Kind == IK_Direct) ||
1491 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1492 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1493 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1494 }
1495
Douglas Gregorb9213832008-12-15 21:24:18 +00001496 // FIXME: When we decide not to synthesize the implicitly-declared
1497 // constructors, we'll need to make them appear here.
1498
Douglas Gregor5870a952008-11-03 20:45:27 +00001499 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001500 switch (BestViableFunction(CandidateSet, Best)) {
1501 case OR_Success:
1502 // We found a constructor. Return it.
1503 return cast<CXXConstructorDecl>(Best->Function);
1504
1505 case OR_No_Viable_Function:
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001506 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1507 << InitEntity << (unsigned)CandidateSet.size() << Range;
1508 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001509 return 0;
1510
1511 case OR_Ambiguous:
Chris Lattner77d52da2008-11-20 06:06:08 +00001512 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001513 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1514 return 0;
1515 }
1516
1517 return 0;
1518}
1519
Douglas Gregor81c29152008-10-29 00:13:59 +00001520/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1521/// determine whether they are reference-related,
1522/// reference-compatible, reference-compatible with added
1523/// qualification, or incompatible, for use in C++ initialization by
1524/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1525/// type, and the first type (T1) is the pointee type of the reference
1526/// type being initialized.
1527Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001528Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1529 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001530 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1531 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1532
1533 T1 = Context.getCanonicalType(T1);
1534 T2 = Context.getCanonicalType(T2);
1535 QualType UnqualT1 = T1.getUnqualifiedType();
1536 QualType UnqualT2 = T2.getUnqualifiedType();
1537
1538 // C++ [dcl.init.ref]p4:
1539 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1540 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1541 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001542 if (UnqualT1 == UnqualT2)
1543 DerivedToBase = false;
1544 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1545 DerivedToBase = true;
1546 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001547 return Ref_Incompatible;
1548
1549 // At this point, we know that T1 and T2 are reference-related (at
1550 // least).
1551
1552 // C++ [dcl.init.ref]p4:
1553 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1554 // reference-related to T2 and cv1 is the same cv-qualification
1555 // as, or greater cv-qualification than, cv2. For purposes of
1556 // overload resolution, cases for which cv1 is greater
1557 // cv-qualification than cv2 are identified as
1558 // reference-compatible with added qualification (see 13.3.3.2).
1559 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1560 return Ref_Compatible;
1561 else if (T1.isMoreQualifiedThan(T2))
1562 return Ref_Compatible_With_Added_Qualification;
1563 else
1564 return Ref_Related;
1565}
1566
1567/// CheckReferenceInit - Check the initialization of a reference
1568/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1569/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001570/// list), and DeclType is the type of the declaration. When ICS is
1571/// non-null, this routine will compute the implicit conversion
1572/// sequence according to C++ [over.ics.ref] and will not produce any
1573/// diagnostics; when ICS is null, it will emit diagnostics when any
1574/// errors are found. Either way, a return value of true indicates
1575/// that there was a failure, a return value of false indicates that
1576/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001577///
1578/// When @p SuppressUserConversions, user-defined conversions are
1579/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001580bool
1581Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001582 ImplicitConversionSequence *ICS,
1583 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001584 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1585
1586 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1587 QualType T2 = Init->getType();
1588
Douglas Gregor45014fd2008-11-10 20:40:00 +00001589 // If the initializer is the address of an overloaded function, try
1590 // to resolve the overloaded function. If all goes well, T2 is the
1591 // type of the resulting function.
1592 if (T2->isOverloadType()) {
1593 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1594 ICS != 0);
1595 if (Fn) {
1596 // Since we're performing this reference-initialization for
1597 // real, update the initializer with the resulting function.
1598 if (!ICS)
1599 FixOverloadedFunctionReference(Init, Fn);
1600
1601 T2 = Fn->getType();
1602 }
1603 }
1604
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001605 // Compute some basic properties of the types and the initializer.
1606 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001607 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001608 ReferenceCompareResult RefRelationship
1609 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1610
1611 // Most paths end in a failed conversion.
1612 if (ICS)
1613 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001614
1615 // C++ [dcl.init.ref]p5:
1616 // A reference to type “cv1 T1” is initialized by an expression
1617 // of type “cv2 T2” as follows:
1618
1619 // -- If the initializer expression
1620
1621 bool BindsDirectly = false;
1622 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1623 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001624 //
1625 // Note that the bit-field check is skipped if we are just computing
1626 // the implicit conversion sequence (C++ [over.best.ics]p2).
1627 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1628 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001629 BindsDirectly = true;
1630
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001631 if (ICS) {
1632 // C++ [over.ics.ref]p1:
1633 // When a parameter of reference type binds directly (8.5.3)
1634 // to an argument expression, the implicit conversion sequence
1635 // is the identity conversion, unless the argument expression
1636 // has a type that is a derived class of the parameter type,
1637 // in which case the implicit conversion sequence is a
1638 // derived-to-base Conversion (13.3.3.1).
1639 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1640 ICS->Standard.First = ICK_Identity;
1641 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1642 ICS->Standard.Third = ICK_Identity;
1643 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1644 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001645 ICS->Standard.ReferenceBinding = true;
1646 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001647
1648 // Nothing more to do: the inaccessibility/ambiguity check for
1649 // derived-to-base conversions is suppressed when we're
1650 // computing the implicit conversion sequence (C++
1651 // [over.best.ics]p2).
1652 return false;
1653 } else {
1654 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001655 // FIXME: Binding to a subobject of the lvalue is going to require
1656 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001657 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001658 }
1659 }
1660
1661 // -- has a class type (i.e., T2 is a class type) and can be
1662 // implicitly converted to an lvalue of type “cv3 T3,”
1663 // where “cv1 T1” is reference-compatible with “cv3 T3”
1664 // 92) (this conversion is selected by enumerating the
1665 // applicable conversion functions (13.3.1.6) and choosing
1666 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001667 if (!SuppressUserConversions && T2->isRecordType()) {
1668 // FIXME: Look for conversions in base classes!
1669 CXXRecordDecl *T2RecordDecl
1670 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001671
Douglas Gregore6985fe2008-11-10 16:14:15 +00001672 OverloadCandidateSet CandidateSet;
1673 OverloadedFunctionDecl *Conversions
1674 = T2RecordDecl->getConversionFunctions();
1675 for (OverloadedFunctionDecl::function_iterator Func
1676 = Conversions->function_begin();
1677 Func != Conversions->function_end(); ++Func) {
1678 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1679
1680 // If the conversion function doesn't return a reference type,
1681 // it can't be considered for this conversion.
1682 // FIXME: This will change when we support rvalue references.
1683 if (Conv->getConversionType()->isReferenceType())
1684 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1685 }
1686
1687 OverloadCandidateSet::iterator Best;
1688 switch (BestViableFunction(CandidateSet, Best)) {
1689 case OR_Success:
1690 // This is a direct binding.
1691 BindsDirectly = true;
1692
1693 if (ICS) {
1694 // C++ [over.ics.ref]p1:
1695 //
1696 // [...] If the parameter binds directly to the result of
1697 // applying a conversion function to the argument
1698 // expression, the implicit conversion sequence is a
1699 // user-defined conversion sequence (13.3.3.1.2), with the
1700 // second standard conversion sequence either an identity
1701 // conversion or, if the conversion function returns an
1702 // entity of a type that is a derived class of the parameter
1703 // type, a derived-to-base Conversion.
1704 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1705 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1706 ICS->UserDefined.After = Best->FinalConversion;
1707 ICS->UserDefined.ConversionFunction = Best->Function;
1708 assert(ICS->UserDefined.After.ReferenceBinding &&
1709 ICS->UserDefined.After.DirectBinding &&
1710 "Expected a direct reference binding!");
1711 return false;
1712 } else {
1713 // Perform the conversion.
1714 // FIXME: Binding to a subobject of the lvalue is going to require
1715 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001716 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001717 }
1718 break;
1719
1720 case OR_Ambiguous:
1721 assert(false && "Ambiguous reference binding conversions not implemented.");
1722 return true;
1723
1724 case OR_No_Viable_Function:
1725 // There was no suitable conversion; continue with other checks.
1726 break;
1727 }
1728 }
1729
Douglas Gregor81c29152008-10-29 00:13:59 +00001730 if (BindsDirectly) {
1731 // C++ [dcl.init.ref]p4:
1732 // [...] In all cases where the reference-related or
1733 // reference-compatible relationship of two types is used to
1734 // establish the validity of a reference binding, and T1 is a
1735 // base class of T2, a program that necessitates such a binding
1736 // is ill-formed if T1 is an inaccessible (clause 11) or
1737 // ambiguous (10.2) base class of T2.
1738 //
1739 // Note that we only check this condition when we're allowed to
1740 // complain about errors, because we should not be checking for
1741 // ambiguity (or inaccessibility) unless the reference binding
1742 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001743 if (DerivedToBase)
1744 return CheckDerivedToBaseConversion(T2, T1,
1745 Init->getSourceRange().getBegin(),
1746 Init->getSourceRange());
1747 else
1748 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001749 }
1750
1751 // -- Otherwise, the reference shall be to a non-volatile const
1752 // type (i.e., cv1 shall be const).
1753 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001754 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001755 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001756 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001757 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1758 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001759 return true;
1760 }
1761
1762 // -- If the initializer expression is an rvalue, with T2 a
1763 // class type, and “cv1 T1” is reference-compatible with
1764 // “cv2 T2,” the reference is bound in one of the
1765 // following ways (the choice is implementation-defined):
1766 //
1767 // -- The reference is bound to the object represented by
1768 // the rvalue (see 3.10) or to a sub-object within that
1769 // object.
1770 //
1771 // -- A temporary of type “cv1 T2” [sic] is created, and
1772 // a constructor is called to copy the entire rvalue
1773 // object into the temporary. The reference is bound to
1774 // the temporary or to a sub-object within the
1775 // temporary.
1776 //
1777 //
1778 // The constructor that would be used to make the copy
1779 // shall be callable whether or not the copy is actually
1780 // done.
1781 //
1782 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1783 // freedom, so we will always take the first option and never build
1784 // a temporary in this case. FIXME: We will, however, have to check
1785 // for the presence of a copy constructor in C++98/03 mode.
1786 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001787 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1788 if (ICS) {
1789 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1790 ICS->Standard.First = ICK_Identity;
1791 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1792 ICS->Standard.Third = ICK_Identity;
1793 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1794 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001795 ICS->Standard.ReferenceBinding = true;
1796 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001797 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001798 // FIXME: Binding to a subobject of the rvalue is going to require
1799 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001800 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001801 }
1802 return false;
1803 }
1804
1805 // -- Otherwise, a temporary of type “cv1 T1” is created and
1806 // initialized from the initializer expression using the
1807 // rules for a non-reference copy initialization (8.5). The
1808 // reference is then bound to the temporary. If T1 is
1809 // reference-related to T2, cv1 must be the same
1810 // cv-qualification as, or greater cv-qualification than,
1811 // cv2; otherwise, the program is ill-formed.
1812 if (RefRelationship == Ref_Related) {
1813 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1814 // we would be reference-compatible or reference-compatible with
1815 // added qualification. But that wasn't the case, so the reference
1816 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001817 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001818 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001819 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001820 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1821 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001822 return true;
1823 }
1824
1825 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001826 if (ICS) {
1827 /// C++ [over.ics.ref]p2:
1828 ///
1829 /// When a parameter of reference type is not bound directly to
1830 /// an argument expression, the conversion sequence is the one
1831 /// required to convert the argument expression to the
1832 /// underlying type of the reference according to
1833 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1834 /// to copy-initializing a temporary of the underlying type with
1835 /// the argument expression. Any difference in top-level
1836 /// cv-qualification is subsumed by the initialization itself
1837 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001838 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001839 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1840 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001841 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001842 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001843}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001844
1845/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1846/// of this overloaded operator is well-formed. If so, returns false;
1847/// otherwise, emits appropriate diagnostics and returns true.
1848bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001849 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00001850 "Expected an overloaded operator declaration");
1851
Douglas Gregore60e5d32008-11-06 22:13:31 +00001852 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1853
1854 // C++ [over.oper]p5:
1855 // The allocation and deallocation functions, operator new,
1856 // operator new[], operator delete and operator delete[], are
1857 // described completely in 3.7.3. The attributes and restrictions
1858 // found in the rest of this subclause do not apply to them unless
1859 // explicitly stated in 3.7.3.
1860 // FIXME: Write a separate routine for checking this. For now, just
1861 // allow it.
1862 if (Op == OO_New || Op == OO_Array_New ||
1863 Op == OO_Delete || Op == OO_Array_Delete)
1864 return false;
1865
1866 // C++ [over.oper]p6:
1867 // An operator function shall either be a non-static member
1868 // function or be a non-member function and have at least one
1869 // parameter whose type is a class, a reference to a class, an
1870 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001871 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1872 if (MethodDecl->isStatic())
1873 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00001874 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001875 } else {
1876 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001877 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1878 ParamEnd = FnDecl->param_end();
1879 Param != ParamEnd; ++Param) {
1880 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001881 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1882 ClassOrEnumParam = true;
1883 break;
1884 }
1885 }
1886
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001887 if (!ClassOrEnumParam)
1888 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001889 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00001890 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001891 }
1892
1893 // C++ [over.oper]p8:
1894 // An operator function cannot have default arguments (8.3.6),
1895 // except where explicitly stated below.
1896 //
1897 // Only the function-call operator allows default arguments
1898 // (C++ [over.call]p1).
1899 if (Op != OO_Call) {
1900 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1901 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001902 if (Expr *DefArg = (*Param)->getDefaultArg())
1903 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00001904 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00001905 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001906 }
1907 }
1908
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001909 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1910 { false, false, false }
1911#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1912 , { Unary, Binary, MemberOnly }
1913#include "clang/Basic/OperatorKinds.def"
1914 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00001915
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001916 bool CanBeUnaryOperator = OperatorUses[Op][0];
1917 bool CanBeBinaryOperator = OperatorUses[Op][1];
1918 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00001919
1920 // C++ [over.oper]p8:
1921 // [...] Operator functions cannot have more or fewer parameters
1922 // than the number required for the corresponding operator, as
1923 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001924 unsigned NumParams = FnDecl->getNumParams()
1925 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001926 if (Op != OO_Call &&
1927 ((NumParams == 1 && !CanBeUnaryOperator) ||
1928 (NumParams == 2 && !CanBeBinaryOperator) ||
1929 (NumParams < 1) || (NumParams > 2))) {
1930 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00001931 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001932 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00001933 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001934 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00001935 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001936 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00001937 assert(CanBeBinaryOperator &&
1938 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00001939 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001940 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001941
Chris Lattnerbb002332008-11-21 07:57:12 +00001942 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00001943 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00001944 }
1945
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001946 // Overloaded operators other than operator() cannot be variadic.
1947 if (Op != OO_Call &&
1948 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001949 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00001950 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001951 }
1952
1953 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001954 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1955 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001956 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00001957 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00001958 }
1959
1960 // C++ [over.inc]p1:
1961 // The user-defined function called operator++ implements the
1962 // prefix and postfix ++ operator. If this function is a member
1963 // function with no parameters, or a non-member function with one
1964 // parameter of class or enumeration type, it defines the prefix
1965 // increment operator ++ for objects of that type. If the function
1966 // is a member function with one parameter (which shall be of type
1967 // int) or a non-member function with two parameters (the second
1968 // of which shall be of type int), it defines the postfix
1969 // increment operator ++ for objects of that type.
1970 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1971 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1972 bool ParamIsInt = false;
1973 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1974 ParamIsInt = BT->getKind() == BuiltinType::Int;
1975
Chris Lattnera7021ee2008-11-21 07:50:02 +00001976 if (!ParamIsInt)
1977 return Diag(LastParam->getLocation(),
1978 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001979 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001980 }
1981
Douglas Gregor682a8cf2008-11-17 16:14:12 +00001982 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00001983}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00001984
Chris Lattner9bb9abf2008-12-17 07:13:27 +00001985/// ActOnLinkageSpec - Parsed a C++ linkage-specification that
1986/// contained braces. Lang/StrSize contains the language string that
1987/// was parsed at location Loc. Decls/NumDecls provides the
1988/// declarations parsed inside the linkage specification.
1989Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
1990 SourceLocation LBrace,
1991 SourceLocation RBrace,
1992 const char *Lang,
1993 unsigned StrSize,
1994 DeclTy **Decls, unsigned NumDecls) {
1995 LinkageSpecDecl::LanguageIDs Language;
1996 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1997 Language = LinkageSpecDecl::lang_c;
1998 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1999 Language = LinkageSpecDecl::lang_cxx;
2000 else {
2001 Diag(Loc, diag::err_bad_language);
2002 return 0;
2003 }
2004
2005 // FIXME: Add all the various semantics of linkage specifications
2006
2007 return LinkageSpecDecl::Create(Context, Loc, Language,
2008 (Decl **)Decls, NumDecls);
2009}
2010
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002011Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
2012 const char *Lang, unsigned StrSize,
2013 DeclTy *D) {
2014 LinkageSpecDecl::LanguageIDs Language;
2015 Decl *dcl = static_cast<Decl *>(D);
2016 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2017 Language = LinkageSpecDecl::lang_c;
2018 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2019 Language = LinkageSpecDecl::lang_cxx;
2020 else {
2021 Diag(Loc, diag::err_bad_language);
2022 return 0;
2023 }
2024
2025 // FIXME: Add all the various semantics of linkage specifications
2026 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
2027}
2028