blob: 29605b6485f8a2adfdbf309ebca5a2b4ca09a166 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner8123a952008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000025#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner8123a952008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattner9e979552008-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 Lattnerb77792e2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000043
Chris Lattner9e979552008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000051 };
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-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 Lattnerb77792e2008-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 Lattner9e979552008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000060 }
61
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Lattnerfa25bbb2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000087 }
Chris Lattner8123a952008-04-10 02:22:51 +000088
Douglas Gregor3996f232008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattner9e979552008-04-12 23:52:44 +000091
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-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 Lattner3d1cee32008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattner3d1cee32008-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 Lattner3d1cee32008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregoreb704f22008-11-04 13:57:51 +0000128 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
129 "in default argument");
Chris Lattner3d1cee32008-04-08 05:04:30 +0000130 if (DefaultArgPtr != DefaultArg.get()) {
131 DefaultArg.take();
132 DefaultArg.reset(DefaultArgPtr);
133 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000134 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000135 return;
136 }
137
Chris Lattner8123a952008-04-10 02:22:51 +0000138 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000139 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000140 if (DefaultArgChecker.Visit(DefaultArg.get())) {
141 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000142 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000143 }
Chris Lattner8123a952008-04-10 02:22:51 +0000144
Chris Lattner3d1cee32008-04-08 05:04:30 +0000145 // Okay: add the default argument to the parameter
146 Param->setDefaultArg(DefaultArg.take());
147}
148
Douglas Gregor72b505b2008-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 Gregor6d6eb572008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000174 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
175 << Param->getDefaultArg()->getSourceRange();
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000176 Param->setDefaultArg(0);
Douglas Gregor72b505b2008-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 Gregor6d6eb572008-05-07 04:49:29 +0000183 }
184 }
185 }
186 }
187}
188
Chris Lattner3d1cee32008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000213 diag::err_param_default_argument_redefinition)
214 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000215 Diag(OldParam->getLocation(), diag::note_previous_definition);
Chris Lattner3d1cee32008-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 Gregor72b505b2008-12-16 21:30:33 +0000249 if (Param->isInvalidDecl())
250 /* We already complained about this parameter. */;
251 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000252 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000253 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000254 << Param->getIdentifier();
Chris Lattner3d1cee32008-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 Gregore37ac4f2008-04-13 21:30:24 +0000277
Douglas Gregorb48fe382008-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.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000282bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
283 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-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 Gregorb48fe382008-10-31 09:07:45 +0000292 return &II == CurDecl->getIdentifier();
293 else
294 return false;
295}
296
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000302Sema::BaseResult
303Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
304 bool Virtual, AccessSpecifier Access,
305 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000310 if (!BaseType->isRecordType())
311 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000312
313 // C++ [class.union]p1:
314 // A union shall not be used as a base class.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000315 if (BaseType->isUnionType())
316 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000317
318 // C++ [class.union]p1:
319 // A union shall not have base classes.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000320 if (Decl->isUnion())
321 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
322 << SpecifierRange;
Douglas Gregore37ac4f2008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000327 if (BaseType->isIncompleteType())
328 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000329
Sebastian Redld93f0dd2008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000335 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000336 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000337
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000338 // Create the base specifier.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000339 return new CXXBaseSpecifier(SpecifierRange, Virtual,
340 BaseType->isClassType(), Access, BaseType);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000341}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000342
Douglas Gregorf8268ae2008-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 Gregor57c856b2008-10-23 18:13:27 +0000353 // that the key is always the unqualified canonical type of the base
354 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000355 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
356
357 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000358 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
359 unsigned NumGoodBases = 0;
360 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000361 QualType NewBaseType
Douglas Gregor57c856b2008-10-23 18:13:27 +0000362 = Context.getCanonicalType(BaseSpecs[idx]->getType());
363 NewBaseType = NewBaseType.getUnqualifiedType();
364
Douglas Gregorf8268ae2008-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 Gregor57c856b2008-10-23 18:13:27 +0000369 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000370 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000371 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000372 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor57c856b2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000377 } else {
378 // Okay, add this new base class.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000379 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
380 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorf8268ae2008-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 Gregor57c856b2008-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 Gregore37ac4f2008-04-13 21:30:24 +0000392}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000393
Argyrios Kyrtzidis07952322008-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 Gregorb48fe382008-10-31 09:07:45 +0000401 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Douglas Gregor44b43212008-12-11 16:49:14 +0000402 PushDeclContext(S, Dcl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000403 FieldCollector->StartClass();
Douglas Gregorb48fe382008-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 Gregor55c60952008-11-10 14:41:22 +0000411 PushOnScopeChains(Dcl, S);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000412 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000413}
414
415/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
416/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
417/// bitfield width if there is one and 'InitExpr' specifies the initializer if
418/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
419/// declarators on it.
420///
Douglas Gregor72b505b2008-12-16 21:30:33 +0000421/// FIXME: The note below is out-of-date.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000422/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
423/// an instance field is declared, a new CXXFieldDecl is created but the method
424/// does *not* return it; it returns LastInGroup instead. The other C++ members
425/// (which are all ScopedDecls) are returned after appending them to
426/// LastInGroup.
427Sema::DeclTy *
428Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
429 ExprTy *BW, ExprTy *InitExpr,
430 DeclTy *LastInGroup) {
431 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000432 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000433 Expr *BitWidth = static_cast<Expr*>(BW);
434 Expr *Init = static_cast<Expr*>(InitExpr);
435 SourceLocation Loc = D.getIdentifierLoc();
436
Sebastian Redl669d5d72008-11-14 23:42:31 +0000437 bool isFunc = D.isFunctionDeclarator();
438
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000439 // C++ 9.2p6: A member shall not be declared to have automatic storage
440 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000441 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
442 // data members and cannot be applied to names declared const or static,
443 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000444 switch (DS.getStorageClassSpec()) {
445 case DeclSpec::SCS_unspecified:
446 case DeclSpec::SCS_typedef:
447 case DeclSpec::SCS_static:
448 // FALL THROUGH.
449 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000450 case DeclSpec::SCS_mutable:
451 if (isFunc) {
452 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000453 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000454 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000455 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
456
Sebastian Redla11f42f2008-11-17 23:24:37 +0000457 // FIXME: It would be nicer if the keyword was ignored only for this
458 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000459 D.getMutableDeclSpec().ClearStorageClassSpecs();
460 } else {
461 QualType T = GetTypeForDeclarator(D, S);
462 diag::kind err = static_cast<diag::kind>(0);
463 if (T->isReferenceType())
464 err = diag::err_mutable_reference;
465 else if (T.isConstQualified())
466 err = diag::err_mutable_const;
467 if (err != 0) {
468 if (DS.getStorageClassSpecLoc().isValid())
469 Diag(DS.getStorageClassSpecLoc(), err);
470 else
471 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000472 // FIXME: It would be nicer if the keyword was ignored only for this
473 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000474 D.getMutableDeclSpec().ClearStorageClassSpecs();
475 }
476 }
477 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000478 default:
479 if (DS.getStorageClassSpecLoc().isValid())
480 Diag(DS.getStorageClassSpecLoc(),
481 diag::err_storageclass_invalid_for_member);
482 else
483 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
484 D.getMutableDeclSpec().ClearStorageClassSpecs();
485 }
486
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000487 if (!isFunc &&
488 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
489 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000490 // Check also for this case:
491 //
492 // typedef int f();
493 // f a;
494 //
495 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
496 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
497 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000498
Sebastian Redl669d5d72008-11-14 23:42:31 +0000499 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
500 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000501 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000502
503 Decl *Member;
504 bool InvalidDecl = false;
505
506 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +0000507 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
508 Loc, D, BitWidth));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000509 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000510 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000511
512 if (!Member) return LastInGroup;
513
Douglas Gregor10bd3682008-11-17 22:58:34 +0000514 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000515
516 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
517 // specific methods. Use a wrapper class that can be used with all C++ class
518 // member decls.
519 CXXClassMemberWrapper(Member).setAccess(AS);
520
Douglas Gregor64bffa92008-11-05 16:20:31 +0000521 // C++ [dcl.init.aggr]p1:
522 // An aggregate is an array or a class (clause 9) with [...] no
523 // private or protected non-static data members (clause 11).
524 if (isInstField && (AS == AS_private || AS == AS_protected))
525 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
526
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000527 if (DS.isVirtualSpecified()) {
528 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
529 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
530 InvalidDecl = true;
531 } else {
532 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
533 CurClass->setAggregate(false);
534 CurClass->setPolymorphic(true);
535 }
536 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000537
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000538 if (BitWidth) {
539 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
540 // constant-expression be a value equal to zero.
541 // FIXME: Check this.
542
543 if (D.isFunctionDeclarator()) {
544 // FIXME: Emit diagnostic about only constructors taking base initializers
545 // or something similar, when constructor support is in place.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000546 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000547 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000548 InvalidDecl = true;
549
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000550 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000551 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000552 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000553 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000554 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000555 InvalidDecl = true;
556 }
557
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000558 } else if (isa<FunctionDecl>(Member)) {
559 // A function typedef ("typedef int f(); f a;").
560 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000561 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000562 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000563 InvalidDecl = true;
564
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000565 } else if (isa<TypedefDecl>(Member)) {
566 // "cannot declare 'A' to be a bit-field type"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000567 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlssona75023d2008-12-06 20:05:35 +0000568 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000569 InvalidDecl = true;
570
571 } else {
572 assert(isa<CXXClassVarDecl>(Member) &&
573 "Didn't we cover all member kinds?");
574 // C++ 9.6p3: A bit-field shall not be a static member.
575 // "static member 'A' cannot be a bit-field"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000576 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlssona75023d2008-12-06 20:05:35 +0000577 << Name << BitWidth->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000578 InvalidDecl = true;
579 }
580 }
581
582 if (Init) {
583 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
584 // if it declares a static member of const integral or const enumeration
585 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000586 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
587 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000588 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000589 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000590 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
591 CVD->getType()->isIntegralType()) {
592 // constant-initializer
593 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000594 InvalidDecl = true;
595
596 } else {
597 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000598 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000599 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000600 InvalidDecl = true;
601 }
602
603 } else {
604 // not static member.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000605 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000606 << Name << Init->getSourceRange();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000607 InvalidDecl = true;
608 }
609 }
610
611 if (InvalidDecl)
612 Member->setInvalidDecl();
613
614 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000615 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000616 return LastInGroup;
617 }
618 return Member;
619}
620
Douglas Gregor7ad83902008-11-05 04:29:56 +0000621/// ActOnMemInitializer - Handle a C++ member initializer.
622Sema::MemInitResult
623Sema::ActOnMemInitializer(DeclTy *ConstructorD,
624 Scope *S,
625 IdentifierInfo *MemberOrBase,
626 SourceLocation IdLoc,
627 SourceLocation LParenLoc,
628 ExprTy **Args, unsigned NumArgs,
629 SourceLocation *CommaLocs,
630 SourceLocation RParenLoc) {
631 CXXConstructorDecl *Constructor
632 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
633 if (!Constructor) {
634 // The user wrote a constructor initializer on a function that is
635 // not a C++ constructor. Ignore the error for now, because we may
636 // have more member initializers coming; we'll diagnose it just
637 // once in ActOnMemInitializers.
638 return true;
639 }
640
641 CXXRecordDecl *ClassDecl = Constructor->getParent();
642
643 // C++ [class.base.init]p2:
644 // Names in a mem-initializer-id are looked up in the scope of the
645 // constructor’s class and, if not found in that scope, are looked
646 // up in the scope containing the constructor’s
647 // definition. [Note: if the constructor’s class contains a member
648 // with the same name as a direct or virtual base class of the
649 // class, a mem-initializer-id naming the member or base class and
650 // composed of a single identifier refers to the class member. A
651 // mem-initializer-id for the hidden base class may be specified
652 // using a qualified name. ]
653 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000654 FieldDecl *Member = 0;
655 DeclContext::lookup_result Result = ClassDecl->lookup(Context, MemberOrBase);
656 if (Result.first != Result.second)
657 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000658
659 // FIXME: Handle members of an anonymous union.
660
661 if (Member) {
662 // FIXME: Perform direct initialization of the member.
663 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
664 }
665
666 // It didn't name a member, so see if it names a class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000667 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000668 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000669 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
670 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000671
672 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
673 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000674 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000675 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000676
677 // C++ [class.base.init]p2:
678 // [...] Unless the mem-initializer-id names a nonstatic data
679 // member of the constructor’s class or a direct or virtual base
680 // of that class, the mem-initializer is ill-formed. A
681 // mem-initializer-list can initialize a base class using any
682 // name that denotes that base class type.
683
684 // First, check for a direct base class.
685 const CXXBaseSpecifier *DirectBaseSpec = 0;
686 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
687 Base != ClassDecl->bases_end(); ++Base) {
688 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
689 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
690 // We found a direct base of this type. That's what we're
691 // initializing.
692 DirectBaseSpec = &*Base;
693 break;
694 }
695 }
696
697 // Check for a virtual base class.
698 // FIXME: We might be able to short-circuit this if we know in
699 // advance that there are no virtual bases.
700 const CXXBaseSpecifier *VirtualBaseSpec = 0;
701 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
702 // We haven't found a base yet; search the class hierarchy for a
703 // virtual base class.
704 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
705 /*DetectVirtual=*/false);
706 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
707 for (BasePaths::paths_iterator Path = Paths.begin();
708 Path != Paths.end(); ++Path) {
709 if (Path->back().Base->isVirtual()) {
710 VirtualBaseSpec = Path->back().Base;
711 break;
712 }
713 }
714 }
715 }
716
717 // C++ [base.class.init]p2:
718 // If a mem-initializer-id is ambiguous because it designates both
719 // a direct non-virtual base class and an inherited virtual base
720 // class, the mem-initializer is ill-formed.
721 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000722 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
723 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000724
725 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
726}
727
728
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000729void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
730 DeclTy *TagDecl,
731 SourceLocation LBrac,
732 SourceLocation RBrac) {
733 ActOnFields(S, RLoc, TagDecl,
734 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000735 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000736}
737
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000738/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
739/// special functions, such as the default constructor, copy
740/// constructor, or destructor, to the given C++ class (C++
741/// [special]p1). This routine can only be executed just before the
742/// definition of the class is complete.
743void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000744 QualType ClassType = Context.getTypeDeclType(ClassDecl);
745 ClassType = Context.getCanonicalType(ClassType);
746
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000747 if (!ClassDecl->hasUserDeclaredConstructor()) {
748 // C++ [class.ctor]p5:
749 // A default constructor for a class X is a constructor of class X
750 // that can be called without an argument. If there is no
751 // user-declared constructor for class X, a default constructor is
752 // implicitly declared. An implicitly-declared default constructor
753 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000754 DeclarationName Name
755 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000756 CXXConstructorDecl *DefaultCon =
757 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000758 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000759 Context.getFunctionType(Context.VoidTy,
760 0, 0, false, 0),
761 /*isExplicit=*/false,
762 /*isInline=*/true,
763 /*isImplicitlyDeclared=*/true);
764 DefaultCon->setAccess(AS_public);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000765 ClassDecl->addDecl(Context, DefaultCon);
766
767 // Notify the class that we've added a constructor.
768 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000769 }
770
771 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
772 // C++ [class.copy]p4:
773 // If the class definition does not explicitly declare a copy
774 // constructor, one is declared implicitly.
775
776 // C++ [class.copy]p5:
777 // The implicitly-declared copy constructor for a class X will
778 // have the form
779 //
780 // X::X(const X&)
781 //
782 // if
783 bool HasConstCopyConstructor = true;
784
785 // -- each direct or virtual base class B of X has a copy
786 // constructor whose first parameter is of type const B& or
787 // const volatile B&, and
788 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
789 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
790 const CXXRecordDecl *BaseClassDecl
791 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
792 HasConstCopyConstructor
793 = BaseClassDecl->hasConstCopyConstructor(Context);
794 }
795
796 // -- for all the nonstatic data members of X that are of a
797 // class type M (or array thereof), each such class type
798 // has a copy constructor whose first parameter is of type
799 // const M& or const volatile M&.
800 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
801 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
802 QualType FieldType = (*Field)->getType();
803 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
804 FieldType = Array->getElementType();
805 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
806 const CXXRecordDecl *FieldClassDecl
807 = cast<CXXRecordDecl>(FieldClassType->getDecl());
808 HasConstCopyConstructor
809 = FieldClassDecl->hasConstCopyConstructor(Context);
810 }
811 }
812
813 // Otherwise, the implicitly declared copy constructor will have
814 // the form
815 //
816 // X::X(X&)
817 QualType ArgType = Context.getTypeDeclType(ClassDecl);
818 if (HasConstCopyConstructor)
819 ArgType = ArgType.withConst();
820 ArgType = Context.getReferenceType(ArgType);
821
822 // An implicitly-declared copy constructor is an inline public
823 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000824 DeclarationName Name
825 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000826 CXXConstructorDecl *CopyConstructor
827 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000828 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000829 Context.getFunctionType(Context.VoidTy,
830 &ArgType, 1,
831 false, 0),
832 /*isExplicit=*/false,
833 /*isInline=*/true,
834 /*isImplicitlyDeclared=*/true);
835 CopyConstructor->setAccess(AS_public);
836
837 // Add the parameter to the constructor.
838 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
839 ClassDecl->getLocation(),
840 /*IdentifierInfo=*/0,
841 ArgType, VarDecl::None, 0, 0);
842 CopyConstructor->setParams(&FromParam, 1);
843
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000844 ClassDecl->addedConstructor(Context, CopyConstructor);
845 DeclContext::lookup_result Lookup = ClassDecl->lookup(Context, Name);
846 if (Lookup.first == Lookup.second
847 || (!isa<CXXConstructorDecl>(*Lookup.first) &&
848 !isa<OverloadedFunctionDecl>(*Lookup.first)))
849 ClassDecl->addDecl(Context, CopyConstructor);
850 else {
851 OverloadedFunctionDecl *Ovl
852 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first);
853 if (!Ovl) {
854 Ovl = OverloadedFunctionDecl::Create(Context, ClassDecl, Name);
855 Ovl->addOverload(cast<CXXConstructorDecl>(*Lookup.first));
856 ClassDecl->insert(Context, Ovl);
857 }
858
859 Ovl->addOverload(CopyConstructor);
860 ClassDecl->addDecl(Context, CopyConstructor, false);
861 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000862 }
863
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000864 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000865 // C++ [class.dtor]p2:
866 // If a class has no user-declared destructor, a destructor is
867 // declared implicitly. An implicitly-declared destructor is an
868 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000869 DeclarationName Name
870 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000871 CXXDestructorDecl *Destructor
872 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000873 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000874 Context.getFunctionType(Context.VoidTy,
875 0, 0, false, 0),
876 /*isInline=*/true,
877 /*isImplicitlyDeclared=*/true);
878 Destructor->setAccess(AS_public);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000879 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000880 }
881
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000882 // FIXME: Implicit copy assignment operator
883}
884
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000885void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000886 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000887 FieldCollector->FinishClass();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000888 AddImplicitlyDeclaredMembersToClass(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000889 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000890
891 // Everything, including inline method definitions, have been parsed.
892 // Let the consumer know of the new TagDecl definition.
893 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000894}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000895
Douglas Gregor72b505b2008-12-16 21:30:33 +0000896/// ActOnStartDelayedCXXMethodDeclaration - We have completed
897/// parsing a top-level (non-nested) C++ class, and we are now
898/// parsing those parts of the given Method declaration that could
899/// not be parsed earlier (C++ [class.mem]p2), such as default
900/// arguments. This action should enter the scope of the given
901/// Method declaration as if we had just parsed the qualified method
902/// name. However, it should not bring the parameters into scope;
903/// that will be performed by ActOnDelayedCXXMethodParameter.
904void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
905 CXXScopeSpec SS;
906 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
907 ActOnCXXEnterDeclaratorScope(S, SS);
908}
909
910/// ActOnDelayedCXXMethodParameter - We've already started a delayed
911/// C++ method declaration. We're (re-)introducing the given
912/// function parameter into scope for use in parsing later parts of
913/// the method declaration. For example, we could see an
914/// ActOnParamDefaultArgument event for this parameter.
915void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
916 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
917 S->AddDecl(Param);
918 if (Param->getDeclName())
919 IdResolver.AddDecl(Param);
920}
921
922/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
923/// processing the delayed method declaration for Method. The method
924/// declaration is now considered finished. There may be a separate
925/// ActOnStartOfFunctionDef action later (not necessarily
926/// immediately!) for this method, if it was also defined inside the
927/// class body.
928void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
929 FunctionDecl *Method = (FunctionDecl*)MethodD;
930 CXXScopeSpec SS;
931 SS.setScopeRep(Method->getDeclContext());
932 ActOnCXXExitDeclaratorScope(S, SS);
933
934 // Now that we have our default arguments, check the constructor
935 // again. It could produce additional diagnostics or affect whether
936 // the class has implicitly-declared destructors, among other
937 // things.
938 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
939 if (CheckConstructor(Constructor))
940 Constructor->setInvalidDecl();
941 }
942
943 // Check the default arguments, which we may have added.
944 if (!Method->isInvalidDecl())
945 CheckCXXDefaultArguments(Method);
946}
947
Douglas Gregor42a552f2008-11-05 20:51:48 +0000948/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +0000949/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +0000950/// R. If there are any errors in the declarator, this routine will
951/// emit diagnostics and return true. Otherwise, it will return
952/// false. Either way, the type @p R will be updated to reflect a
953/// well-formed type for the constructor.
954bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
955 FunctionDecl::StorageClass& SC) {
956 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
957 bool isInvalid = false;
958
959 // C++ [class.ctor]p3:
960 // A constructor shall not be virtual (10.3) or static (9.4). A
961 // constructor can be invoked for a const, volatile or const
962 // volatile object. A constructor shall not be declared const,
963 // volatile, or const volatile (9.3.2).
964 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000965 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
966 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
967 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000968 isInvalid = true;
969 }
970 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000971 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
972 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
973 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000974 isInvalid = true;
975 SC = FunctionDecl::None;
976 }
977 if (D.getDeclSpec().hasTypeSpecifier()) {
978 // Constructors don't have return types, but the parser will
979 // happily parse something like:
980 //
981 // class X {
982 // float X(float);
983 // };
984 //
985 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000986 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
987 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
988 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000989 }
990 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
991 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
992 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000993 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
994 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000995 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000996 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
997 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000998 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000999 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1000 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001001 }
1002
1003 // Rebuild the function type "R" without any type qualifiers (in
1004 // case any of the errors above fired) and with "void" as the
1005 // return type, since constructors don't have return types. We
1006 // *always* have to do this, because GetTypeForDeclarator will
1007 // put in a result type of "int" when none was specified.
1008 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
1009 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1010 Proto->getNumArgs(),
1011 Proto->isVariadic(),
1012 0);
1013
1014 return isInvalid;
1015}
1016
Douglas Gregor72b505b2008-12-16 21:30:33 +00001017/// CheckConstructor - Checks a fully-formed constructor for
1018/// well-formedness, issuing any diagnostics required. Returns true if
1019/// the constructor declarator is invalid.
1020bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1021 if (Constructor->isInvalidDecl())
1022 return true;
1023
1024 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1025 bool Invalid = false;
1026
1027 // C++ [class.copy]p3:
1028 // A declaration of a constructor for a class X is ill-formed if
1029 // its first parameter is of type (optionally cv-qualified) X and
1030 // either there are no other parameters or else all other
1031 // parameters have default arguments.
1032 if ((Constructor->getNumParams() == 1) ||
1033 (Constructor->getNumParams() > 1 &&
1034 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1035 QualType ParamType = Constructor->getParamDecl(0)->getType();
1036 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1037 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1038 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1039 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1040 Invalid = true;
1041 }
1042 }
1043
1044 // Notify the class that we've added a constructor.
1045 ClassDecl->addedConstructor(Context, Constructor);
1046
1047 return Invalid;
1048}
1049
Douglas Gregor42a552f2008-11-05 20:51:48 +00001050/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1051/// the well-formednes of the destructor declarator @p D with type @p
1052/// R. If there are any errors in the declarator, this routine will
1053/// emit diagnostics and return true. Otherwise, it will return
1054/// false. Either way, the type @p R will be updated to reflect a
1055/// well-formed type for the destructor.
1056bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1057 FunctionDecl::StorageClass& SC) {
1058 bool isInvalid = false;
1059
1060 // C++ [class.dtor]p1:
1061 // [...] A typedef-name that names a class is a class-name
1062 // (7.1.3); however, a typedef-name that names a class shall not
1063 // be used as the identifier in the declarator for a destructor
1064 // declaration.
1065 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
1066 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001067 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001068 << TypedefD->getDeclName();
Douglas Gregor55c60952008-11-10 14:41:22 +00001069 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001070 }
1071
1072 // C++ [class.dtor]p2:
1073 // A destructor is used to destroy objects of its class type. A
1074 // destructor takes no parameters, and no return type can be
1075 // specified for it (not even void). The address of a destructor
1076 // shall not be taken. A destructor shall not be static. A
1077 // destructor can be invoked for a const, volatile or const
1078 // volatile object. A destructor shall not be declared const,
1079 // volatile or const volatile (9.3.2).
1080 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001081 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1082 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1083 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001084 isInvalid = true;
1085 SC = FunctionDecl::None;
1086 }
1087 if (D.getDeclSpec().hasTypeSpecifier()) {
1088 // Destructors don't have return types, but the parser will
1089 // happily parse something like:
1090 //
1091 // class X {
1092 // float ~X();
1093 // };
1094 //
1095 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001096 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1097 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1098 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001099 }
1100 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
1101 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1102 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001103 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1104 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001105 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001106 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1107 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001108 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001109 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1110 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001111 }
1112
1113 // Make sure we don't have any parameters.
1114 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1115 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1116
1117 // Delete the parameters.
1118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1119 if (FTI.NumArgs) {
1120 delete [] FTI.ArgInfo;
1121 FTI.NumArgs = 0;
1122 FTI.ArgInfo = 0;
1123 }
1124 }
1125
1126 // Make sure the destructor isn't variadic.
1127 if (R->getAsFunctionTypeProto()->isVariadic())
1128 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1129
1130 // Rebuild the function type "R" without any type qualifiers or
1131 // parameters (in case any of the errors above fired) and with
1132 // "void" as the return type, since destructors don't have return
1133 // types. We *always* have to do this, because GetTypeForDeclarator
1134 // will put in a result type of "int" when none was specified.
1135 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1136
1137 return isInvalid;
1138}
1139
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001140/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1141/// well-formednes of the conversion function declarator @p D with
1142/// type @p R. If there are any errors in the declarator, this routine
1143/// will emit diagnostics and return true. Otherwise, it will return
1144/// false. Either way, the type @p R will be updated to reflect a
1145/// well-formed type for the conversion operator.
1146bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1147 FunctionDecl::StorageClass& SC) {
1148 bool isInvalid = false;
1149
1150 // C++ [class.conv.fct]p1:
1151 // Neither parameter types nor return type can be specified. The
1152 // type of a conversion function (8.3.5) is “function taking no
1153 // parameter returning conversion-type-id.”
1154 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001155 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1156 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1157 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001158 isInvalid = true;
1159 SC = FunctionDecl::None;
1160 }
1161 if (D.getDeclSpec().hasTypeSpecifier()) {
1162 // Conversion functions don't have return types, but the parser will
1163 // happily parse something like:
1164 //
1165 // class X {
1166 // float operator bool();
1167 // };
1168 //
1169 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001170 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1171 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1172 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001173 }
1174
1175 // Make sure we don't have any parameters.
1176 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1177 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1178
1179 // Delete the parameters.
1180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1181 if (FTI.NumArgs) {
1182 delete [] FTI.ArgInfo;
1183 FTI.NumArgs = 0;
1184 FTI.ArgInfo = 0;
1185 }
1186 }
1187
1188 // Make sure the conversion function isn't variadic.
1189 if (R->getAsFunctionTypeProto()->isVariadic())
1190 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1191
1192 // C++ [class.conv.fct]p4:
1193 // The conversion-type-id shall not represent a function type nor
1194 // an array type.
1195 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1196 if (ConvType->isArrayType()) {
1197 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1198 ConvType = Context.getPointerType(ConvType);
1199 } else if (ConvType->isFunctionType()) {
1200 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1201 ConvType = Context.getPointerType(ConvType);
1202 }
1203
1204 // Rebuild the function type "R" without any parameters (in case any
1205 // of the errors above fired) and with the conversion type as the
1206 // return type.
1207 R = Context.getFunctionType(ConvType, 0, 0, false,
1208 R->getAsFunctionTypeProto()->getTypeQuals());
1209
1210 return isInvalid;
1211}
1212
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001213/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1214/// the declaration of the given C++ conversion function. This routine
1215/// is responsible for recording the conversion function in the C++
1216/// class, if possible.
1217Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1218 assert(Conversion && "Expected to receive a conversion function declaration");
1219
Douglas Gregor9d350972008-12-12 08:25:50 +00001220 // Set the lexical context of this conversion function
1221 Conversion->setLexicalDeclContext(CurContext);
1222
1223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001224
1225 // Make sure we aren't redeclaring the conversion function.
1226 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1227 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1228 for (OverloadedFunctionDecl::function_iterator Func
1229 = Conversions->function_begin();
1230 Func != Conversions->function_end(); ++Func) {
1231 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1232 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1233 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1234 Diag(OtherConv->getLocation(),
1235 OtherConv->isThisDeclarationADefinition()?
Chris Lattner5f4a6822008-11-23 23:12:31 +00001236 diag::note_previous_definition
1237 : diag::note_previous_declaration);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001238 Conversion->setInvalidDecl();
1239 return (DeclTy *)Conversion;
1240 }
1241 }
1242
1243 // C++ [class.conv.fct]p1:
1244 // [...] A conversion function is never used to convert a
1245 // (possibly cv-qualified) object to the (possibly cv-qualified)
1246 // same object type (or a reference to it), to a (possibly
1247 // cv-qualified) base class of that type (or a reference to it),
1248 // or to (possibly cv-qualified) void.
1249 // FIXME: Suppress this warning if the conversion function ends up
1250 // being a virtual function that overrides a virtual function in a
1251 // base class.
1252 QualType ClassType
1253 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1254 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1255 ConvType = ConvTypeRef->getPointeeType();
1256 if (ConvType->isRecordType()) {
1257 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1258 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001259 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001260 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001261 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001262 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001263 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001264 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001265 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001266 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001267 }
1268
1269 ClassDecl->addConversionFunction(Context, Conversion);
1270
1271 return (DeclTy *)Conversion;
1272}
1273
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001274//===----------------------------------------------------------------------===//
1275// Namespace Handling
1276//===----------------------------------------------------------------------===//
1277
1278/// ActOnStartNamespaceDef - This is called at the start of a namespace
1279/// definition.
1280Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1281 SourceLocation IdentLoc,
1282 IdentifierInfo *II,
1283 SourceLocation LBrace) {
1284 NamespaceDecl *Namespc =
1285 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1286 Namespc->setLBracLoc(LBrace);
1287
1288 Scope *DeclRegionScope = NamespcScope->getParent();
1289
1290 if (II) {
1291 // C++ [namespace.def]p2:
1292 // The identifier in an original-namespace-definition shall not have been
1293 // previously defined in the declarative region in which the
1294 // original-namespace-definition appears. The identifier in an
1295 // original-namespace-definition is the name of the namespace. Subsequently
1296 // in that declarative region, it is treated as an original-namespace-name.
1297
1298 Decl *PrevDecl =
Douglas Gregor44b43212008-12-11 16:49:14 +00001299 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
1300 /*enableLazyBuiltinCreation=*/false,
1301 /*LookupInParent=*/false);
1302
1303 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1304 // This is an extended namespace definition.
1305 // Attach this namespace decl to the chain of extended namespace
1306 // definitions.
1307 OrigNS->setNextNamespace(Namespc);
1308 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001309
Douglas Gregor44b43212008-12-11 16:49:14 +00001310 // Remove the previous declaration from the scope.
1311 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001312 IdResolver.RemoveDecl(OrigNS);
1313 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001314 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001315 } else if (PrevDecl) {
1316 // This is an invalid name redefinition.
1317 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1318 << Namespc->getDeclName();
1319 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1320 Namespc->setInvalidDecl();
1321 // Continue on to push Namespc as current DeclContext and return it.
1322 }
1323
1324 PushOnScopeChains(Namespc, DeclRegionScope);
1325 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001326 // FIXME: Handle anonymous namespaces
1327 }
1328
1329 // Although we could have an invalid decl (i.e. the namespace name is a
1330 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001331 // FIXME: We should be able to push Namespc here, so that the
1332 // each DeclContext for the namespace has the declarations
1333 // that showed up in that particular namespace definition.
1334 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001335 return Namespc;
1336}
1337
1338/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1339/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1340void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1341 Decl *Dcl = static_cast<Decl *>(D);
1342 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1343 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1344 Namespc->setRBracLoc(RBrace);
1345 PopDeclContext();
1346}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001347
1348
1349/// AddCXXDirectInitializerToDecl - This action is called immediately after
1350/// ActOnDeclarator, when a C++ direct initializer is present.
1351/// e.g: "int x(1);"
1352void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1353 ExprTy **ExprTys, unsigned NumExprs,
1354 SourceLocation *CommaLocs,
1355 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001356 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001357 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001358
1359 // If there is no declaration, there was an error parsing it. Just ignore
1360 // the initializer.
1361 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001362 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001363 delete static_cast<Expr *>(ExprTys[i]);
1364 return;
1365 }
1366
1367 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1368 if (!VDecl) {
1369 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1370 RealDecl->setInvalidDecl();
1371 return;
1372 }
1373
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001374 // We will treat direct-initialization as a copy-initialization:
1375 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001376 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1377 //
1378 // Clients that want to distinguish between the two forms, can check for
1379 // direct initializer using VarDecl::hasCXXDirectInitializer().
1380 // A major benefit is that clients that don't particularly care about which
1381 // exactly form was it (like the CodeGen) can handle both cases without
1382 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001383
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001384 // C++ 8.5p11:
1385 // The form of initialization (using parentheses or '=') is generally
1386 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001387 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001388 QualType DeclInitType = VDecl->getType();
1389 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1390 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001391
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001392 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001393 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001394 = PerformInitializationByConstructor(DeclInitType,
1395 (Expr **)ExprTys, NumExprs,
1396 VDecl->getLocation(),
1397 SourceRange(VDecl->getLocation(),
1398 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001399 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001400 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001401 if (!Constructor) {
1402 RealDecl->setInvalidDecl();
1403 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001404
1405 // Let clients know that initialization was done with a direct
1406 // initializer.
1407 VDecl->setCXXDirectInitializer(true);
1408
1409 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1410 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001411 return;
1412 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001413
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001414 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001415 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1416 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001417 RealDecl->setInvalidDecl();
1418 return;
1419 }
1420
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001421 // Let clients know that initialization was done with a direct initializer.
1422 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001423
1424 assert(NumExprs == 1 && "Expected 1 expression");
1425 // Set the init expression, handles conversions.
Sebastian Redl798d1192008-12-13 16:23:55 +00001426 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001427}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001428
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001429/// PerformInitializationByConstructor - Perform initialization by
1430/// constructor (C++ [dcl.init]p14), which may occur as part of
1431/// direct-initialization or copy-initialization. We are initializing
1432/// an object of type @p ClassType with the given arguments @p
1433/// Args. @p Loc is the location in the source code where the
1434/// initializer occurs (e.g., a declaration, member initializer,
1435/// functional cast, etc.) while @p Range covers the whole
1436/// initialization. @p InitEntity is the entity being initialized,
1437/// which may by the name of a declaration or a type. @p Kind is the
1438/// kind of initialization we're performing, which affects whether
1439/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001440/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001441/// when the initialization fails, emits a diagnostic and returns
1442/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001443CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001444Sema::PerformInitializationByConstructor(QualType ClassType,
1445 Expr **Args, unsigned NumArgs,
1446 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001447 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001448 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001449 const RecordType *ClassRec = ClassType->getAsRecordType();
1450 assert(ClassRec && "Can only initialize a class type here");
1451
1452 // C++ [dcl.init]p14:
1453 //
1454 // If the initialization is direct-initialization, or if it is
1455 // copy-initialization where the cv-unqualified version of the
1456 // source type is the same class as, or a derived class of, the
1457 // class of the destination, constructors are considered. The
1458 // applicable constructors are enumerated (13.3.1.3), and the
1459 // best one is chosen through overload resolution (13.3). The
1460 // constructor so selected is called to initialize the object,
1461 // with the initializer expression(s) as its argument(s). If no
1462 // constructor applies, or the overload resolution is ambiguous,
1463 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001464 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1465 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001466
1467 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001468 DeclarationName ConstructorName
1469 = Context.DeclarationNames.getCXXConstructorName(
1470 Context.getCanonicalType(ClassType.getUnqualifiedType()));
1471 DeclContext::lookup_const_result Lookup
1472 = ClassDecl->lookup(Context, ConstructorName);
1473 if (Lookup.first == Lookup.second)
1474 /* No constructors */;
1475 else if (OverloadedFunctionDecl *Constructors
1476 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) {
1477 for (OverloadedFunctionDecl::function_iterator Con
1478 = Constructors->function_begin();
1479 Con != Constructors->function_end(); ++Con) {
1480 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1481 if ((Kind == IK_Direct) ||
1482 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1483 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1484 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1485 }
1486 } else if (CXXConstructorDecl *Constructor
1487 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001488 if ((Kind == IK_Direct) ||
1489 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1490 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1491 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1492 }
1493
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001494 // FIXME: When we decide not to synthesize the implicitly-declared
1495 // constructors, we'll need to make them appear here.
1496
Douglas Gregor18fe5682008-11-03 20:45:27 +00001497 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001498 switch (BestViableFunction(CandidateSet, Best)) {
1499 case OR_Success:
1500 // We found a constructor. Return it.
1501 return cast<CXXConstructorDecl>(Best->Function);
1502
1503 case OR_No_Viable_Function:
Sebastian Redle4c452c2008-11-22 13:44:36 +00001504 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1505 << InitEntity << (unsigned)CandidateSet.size() << Range;
1506 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001507 return 0;
1508
1509 case OR_Ambiguous:
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001510 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001511 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1512 return 0;
1513 }
1514
1515 return 0;
1516}
1517
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001518/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1519/// determine whether they are reference-related,
1520/// reference-compatible, reference-compatible with added
1521/// qualification, or incompatible, for use in C++ initialization by
1522/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1523/// type, and the first type (T1) is the pointee type of the reference
1524/// type being initialized.
1525Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001526Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1527 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001528 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1529 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1530
1531 T1 = Context.getCanonicalType(T1);
1532 T2 = Context.getCanonicalType(T2);
1533 QualType UnqualT1 = T1.getUnqualifiedType();
1534 QualType UnqualT2 = T2.getUnqualifiedType();
1535
1536 // C++ [dcl.init.ref]p4:
1537 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1538 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1539 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001540 if (UnqualT1 == UnqualT2)
1541 DerivedToBase = false;
1542 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1543 DerivedToBase = true;
1544 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001545 return Ref_Incompatible;
1546
1547 // At this point, we know that T1 and T2 are reference-related (at
1548 // least).
1549
1550 // C++ [dcl.init.ref]p4:
1551 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1552 // reference-related to T2 and cv1 is the same cv-qualification
1553 // as, or greater cv-qualification than, cv2. For purposes of
1554 // overload resolution, cases for which cv1 is greater
1555 // cv-qualification than cv2 are identified as
1556 // reference-compatible with added qualification (see 13.3.3.2).
1557 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1558 return Ref_Compatible;
1559 else if (T1.isMoreQualifiedThan(T2))
1560 return Ref_Compatible_With_Added_Qualification;
1561 else
1562 return Ref_Related;
1563}
1564
1565/// CheckReferenceInit - Check the initialization of a reference
1566/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1567/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001568/// list), and DeclType is the type of the declaration. When ICS is
1569/// non-null, this routine will compute the implicit conversion
1570/// sequence according to C++ [over.ics.ref] and will not produce any
1571/// diagnostics; when ICS is null, it will emit diagnostics when any
1572/// errors are found. Either way, a return value of true indicates
1573/// that there was a failure, a return value of false indicates that
1574/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001575///
1576/// When @p SuppressUserConversions, user-defined conversions are
1577/// suppressed.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001578bool
1579Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001580 ImplicitConversionSequence *ICS,
1581 bool SuppressUserConversions) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001582 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1583
1584 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1585 QualType T2 = Init->getType();
1586
Douglas Gregor904eed32008-11-10 20:40:00 +00001587 // If the initializer is the address of an overloaded function, try
1588 // to resolve the overloaded function. If all goes well, T2 is the
1589 // type of the resulting function.
1590 if (T2->isOverloadType()) {
1591 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1592 ICS != 0);
1593 if (Fn) {
1594 // Since we're performing this reference-initialization for
1595 // real, update the initializer with the resulting function.
1596 if (!ICS)
1597 FixOverloadedFunctionReference(Init, Fn);
1598
1599 T2 = Fn->getType();
1600 }
1601 }
1602
Douglas Gregor15da57e2008-10-29 02:00:59 +00001603 // Compute some basic properties of the types and the initializer.
1604 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001605 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001606 ReferenceCompareResult RefRelationship
1607 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1608
1609 // Most paths end in a failed conversion.
1610 if (ICS)
1611 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001612
1613 // C++ [dcl.init.ref]p5:
1614 // A reference to type “cv1 T1” is initialized by an expression
1615 // of type “cv2 T2” as follows:
1616
1617 // -- If the initializer expression
1618
1619 bool BindsDirectly = false;
1620 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1621 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001622 //
1623 // Note that the bit-field check is skipped if we are just computing
1624 // the implicit conversion sequence (C++ [over.best.ics]p2).
1625 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1626 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001627 BindsDirectly = true;
1628
Douglas Gregor15da57e2008-10-29 02:00:59 +00001629 if (ICS) {
1630 // C++ [over.ics.ref]p1:
1631 // When a parameter of reference type binds directly (8.5.3)
1632 // to an argument expression, the implicit conversion sequence
1633 // is the identity conversion, unless the argument expression
1634 // has a type that is a derived class of the parameter type,
1635 // in which case the implicit conversion sequence is a
1636 // derived-to-base Conversion (13.3.3.1).
1637 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1638 ICS->Standard.First = ICK_Identity;
1639 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1640 ICS->Standard.Third = ICK_Identity;
1641 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1642 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001643 ICS->Standard.ReferenceBinding = true;
1644 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001645
1646 // Nothing more to do: the inaccessibility/ambiguity check for
1647 // derived-to-base conversions is suppressed when we're
1648 // computing the implicit conversion sequence (C++
1649 // [over.best.ics]p2).
1650 return false;
1651 } else {
1652 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001653 // FIXME: Binding to a subobject of the lvalue is going to require
1654 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001655 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001656 }
1657 }
1658
1659 // -- has a class type (i.e., T2 is a class type) and can be
1660 // implicitly converted to an lvalue of type “cv3 T3,”
1661 // where “cv1 T1” is reference-compatible with “cv3 T3”
1662 // 92) (this conversion is selected by enumerating the
1663 // applicable conversion functions (13.3.1.6) and choosing
1664 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001665 if (!SuppressUserConversions && T2->isRecordType()) {
1666 // FIXME: Look for conversions in base classes!
1667 CXXRecordDecl *T2RecordDecl
1668 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001669
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001670 OverloadCandidateSet CandidateSet;
1671 OverloadedFunctionDecl *Conversions
1672 = T2RecordDecl->getConversionFunctions();
1673 for (OverloadedFunctionDecl::function_iterator Func
1674 = Conversions->function_begin();
1675 Func != Conversions->function_end(); ++Func) {
1676 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1677
1678 // If the conversion function doesn't return a reference type,
1679 // it can't be considered for this conversion.
1680 // FIXME: This will change when we support rvalue references.
1681 if (Conv->getConversionType()->isReferenceType())
1682 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1683 }
1684
1685 OverloadCandidateSet::iterator Best;
1686 switch (BestViableFunction(CandidateSet, Best)) {
1687 case OR_Success:
1688 // This is a direct binding.
1689 BindsDirectly = true;
1690
1691 if (ICS) {
1692 // C++ [over.ics.ref]p1:
1693 //
1694 // [...] If the parameter binds directly to the result of
1695 // applying a conversion function to the argument
1696 // expression, the implicit conversion sequence is a
1697 // user-defined conversion sequence (13.3.3.1.2), with the
1698 // second standard conversion sequence either an identity
1699 // conversion or, if the conversion function returns an
1700 // entity of a type that is a derived class of the parameter
1701 // type, a derived-to-base Conversion.
1702 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1703 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1704 ICS->UserDefined.After = Best->FinalConversion;
1705 ICS->UserDefined.ConversionFunction = Best->Function;
1706 assert(ICS->UserDefined.After.ReferenceBinding &&
1707 ICS->UserDefined.After.DirectBinding &&
1708 "Expected a direct reference binding!");
1709 return false;
1710 } else {
1711 // Perform the conversion.
1712 // FIXME: Binding to a subobject of the lvalue is going to require
1713 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001714 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001715 }
1716 break;
1717
1718 case OR_Ambiguous:
1719 assert(false && "Ambiguous reference binding conversions not implemented.");
1720 return true;
1721
1722 case OR_No_Viable_Function:
1723 // There was no suitable conversion; continue with other checks.
1724 break;
1725 }
1726 }
1727
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001728 if (BindsDirectly) {
1729 // C++ [dcl.init.ref]p4:
1730 // [...] In all cases where the reference-related or
1731 // reference-compatible relationship of two types is used to
1732 // establish the validity of a reference binding, and T1 is a
1733 // base class of T2, a program that necessitates such a binding
1734 // is ill-formed if T1 is an inaccessible (clause 11) or
1735 // ambiguous (10.2) base class of T2.
1736 //
1737 // Note that we only check this condition when we're allowed to
1738 // complain about errors, because we should not be checking for
1739 // ambiguity (or inaccessibility) unless the reference binding
1740 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001741 if (DerivedToBase)
1742 return CheckDerivedToBaseConversion(T2, T1,
1743 Init->getSourceRange().getBegin(),
1744 Init->getSourceRange());
1745 else
1746 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001747 }
1748
1749 // -- Otherwise, the reference shall be to a non-volatile const
1750 // type (i.e., cv1 shall be const).
1751 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001752 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001753 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001754 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001755 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1756 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001757 return true;
1758 }
1759
1760 // -- If the initializer expression is an rvalue, with T2 a
1761 // class type, and “cv1 T1” is reference-compatible with
1762 // “cv2 T2,” the reference is bound in one of the
1763 // following ways (the choice is implementation-defined):
1764 //
1765 // -- The reference is bound to the object represented by
1766 // the rvalue (see 3.10) or to a sub-object within that
1767 // object.
1768 //
1769 // -- A temporary of type “cv1 T2” [sic] is created, and
1770 // a constructor is called to copy the entire rvalue
1771 // object into the temporary. The reference is bound to
1772 // the temporary or to a sub-object within the
1773 // temporary.
1774 //
1775 //
1776 // The constructor that would be used to make the copy
1777 // shall be callable whether or not the copy is actually
1778 // done.
1779 //
1780 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1781 // freedom, so we will always take the first option and never build
1782 // a temporary in this case. FIXME: We will, however, have to check
1783 // for the presence of a copy constructor in C++98/03 mode.
1784 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001785 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1786 if (ICS) {
1787 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1788 ICS->Standard.First = ICK_Identity;
1789 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1790 ICS->Standard.Third = ICK_Identity;
1791 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1792 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001793 ICS->Standard.ReferenceBinding = true;
1794 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001795 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001796 // FIXME: Binding to a subobject of the rvalue is going to require
1797 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001798 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001799 }
1800 return false;
1801 }
1802
1803 // -- Otherwise, a temporary of type “cv1 T1” is created and
1804 // initialized from the initializer expression using the
1805 // rules for a non-reference copy initialization (8.5). The
1806 // reference is then bound to the temporary. If T1 is
1807 // reference-related to T2, cv1 must be the same
1808 // cv-qualification as, or greater cv-qualification than,
1809 // cv2; otherwise, the program is ill-formed.
1810 if (RefRelationship == Ref_Related) {
1811 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1812 // we would be reference-compatible or reference-compatible with
1813 // added qualification. But that wasn't the case, so the reference
1814 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001815 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001816 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001817 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001818 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1819 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001820 return true;
1821 }
1822
1823 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001824 if (ICS) {
1825 /// C++ [over.ics.ref]p2:
1826 ///
1827 /// When a parameter of reference type is not bound directly to
1828 /// an argument expression, the conversion sequence is the one
1829 /// required to convert the argument expression to the
1830 /// underlying type of the reference according to
1831 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1832 /// to copy-initializing a temporary of the underlying type with
1833 /// the argument expression. Any difference in top-level
1834 /// cv-qualification is subsumed by the initialization itself
1835 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001836 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001837 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1838 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001839 return PerformImplicitConversion(Init, T1);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001840 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001841}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001842
1843/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1844/// of this overloaded operator is well-formed. If so, returns false;
1845/// otherwise, emits appropriate diagnostics and returns true.
1846bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001847 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001848 "Expected an overloaded operator declaration");
1849
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001850 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1851
1852 // C++ [over.oper]p5:
1853 // The allocation and deallocation functions, operator new,
1854 // operator new[], operator delete and operator delete[], are
1855 // described completely in 3.7.3. The attributes and restrictions
1856 // found in the rest of this subclause do not apply to them unless
1857 // explicitly stated in 3.7.3.
1858 // FIXME: Write a separate routine for checking this. For now, just
1859 // allow it.
1860 if (Op == OO_New || Op == OO_Array_New ||
1861 Op == OO_Delete || Op == OO_Array_Delete)
1862 return false;
1863
1864 // C++ [over.oper]p6:
1865 // An operator function shall either be a non-static member
1866 // function or be a non-member function and have at least one
1867 // parameter whose type is a class, a reference to a class, an
1868 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001869 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1870 if (MethodDecl->isStatic())
1871 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001872 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001873 } else {
1874 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001875 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
1876 ParamEnd = FnDecl->param_end();
1877 Param != ParamEnd; ++Param) {
1878 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001879 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1880 ClassOrEnumParam = true;
1881 break;
1882 }
1883 }
1884
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001885 if (!ClassOrEnumParam)
1886 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001887 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001888 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001889 }
1890
1891 // C++ [over.oper]p8:
1892 // An operator function cannot have default arguments (8.3.6),
1893 // except where explicitly stated below.
1894 //
1895 // Only the function-call operator allows default arguments
1896 // (C++ [over.call]p1).
1897 if (Op != OO_Call) {
1898 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1899 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001900 if (Expr *DefArg = (*Param)->getDefaultArg())
1901 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001902 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001903 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001904 }
1905 }
1906
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001907 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1908 { false, false, false }
1909#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1910 , { Unary, Binary, MemberOnly }
1911#include "clang/Basic/OperatorKinds.def"
1912 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001913
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001914 bool CanBeUnaryOperator = OperatorUses[Op][0];
1915 bool CanBeBinaryOperator = OperatorUses[Op][1];
1916 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001917
1918 // C++ [over.oper]p8:
1919 // [...] Operator functions cannot have more or fewer parameters
1920 // than the number required for the corresponding operator, as
1921 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001922 unsigned NumParams = FnDecl->getNumParams()
1923 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001924 if (Op != OO_Call &&
1925 ((NumParams == 1 && !CanBeUnaryOperator) ||
1926 (NumParams == 2 && !CanBeBinaryOperator) ||
1927 (NumParams < 1) || (NumParams > 2))) {
1928 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00001929 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001930 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001931 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001932 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00001933 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001934 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001935 assert(CanBeBinaryOperator &&
1936 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00001937 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00001938 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001939
Chris Lattner416e46f2008-11-21 07:57:12 +00001940 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001941 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001942 }
1943
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001944 // Overloaded operators other than operator() cannot be variadic.
1945 if (Op != OO_Call &&
1946 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001947 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001948 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001949 }
1950
1951 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001952 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
1953 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001954 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001955 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001956 }
1957
1958 // C++ [over.inc]p1:
1959 // The user-defined function called operator++ implements the
1960 // prefix and postfix ++ operator. If this function is a member
1961 // function with no parameters, or a non-member function with one
1962 // parameter of class or enumeration type, it defines the prefix
1963 // increment operator ++ for objects of that type. If the function
1964 // is a member function with one parameter (which shall be of type
1965 // int) or a non-member function with two parameters (the second
1966 // of which shall be of type int), it defines the postfix
1967 // increment operator ++ for objects of that type.
1968 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1969 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1970 bool ParamIsInt = false;
1971 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1972 ParamIsInt = BT->getKind() == BuiltinType::Int;
1973
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00001974 if (!ParamIsInt)
1975 return Diag(LastParam->getLocation(),
1976 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00001977 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001978 }
1979
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001980 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001981}
Chris Lattner5a003a42008-12-17 07:09:26 +00001982
Chris Lattnercc98eac2008-12-17 07:13:27 +00001983/// ActOnLinkageSpec - Parsed a C++ linkage-specification that
1984/// contained braces. Lang/StrSize contains the language string that
1985/// was parsed at location Loc. Decls/NumDecls provides the
1986/// declarations parsed inside the linkage specification.
1987Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
1988 SourceLocation LBrace,
1989 SourceLocation RBrace,
1990 const char *Lang,
1991 unsigned StrSize,
1992 DeclTy **Decls, unsigned NumDecls) {
1993 LinkageSpecDecl::LanguageIDs Language;
1994 if (strncmp(Lang, "\"C\"", StrSize) == 0)
1995 Language = LinkageSpecDecl::lang_c;
1996 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
1997 Language = LinkageSpecDecl::lang_cxx;
1998 else {
1999 Diag(Loc, diag::err_bad_language);
2000 return 0;
2001 }
2002
2003 // FIXME: Add all the various semantics of linkage specifications
2004
2005 return LinkageSpecDecl::Create(Context, Loc, Language,
2006 (Decl **)Decls, NumDecls);
2007}
2008
Chris Lattner5a003a42008-12-17 07:09:26 +00002009Sema::DeclTy *Sema::ActOnLinkageSpec(SourceLocation Loc,
2010 const char *Lang, unsigned StrSize,
2011 DeclTy *D) {
2012 LinkageSpecDecl::LanguageIDs Language;
2013 Decl *dcl = static_cast<Decl *>(D);
2014 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2015 Language = LinkageSpecDecl::lang_c;
2016 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2017 Language = LinkageSpecDecl::lang_cxx;
2018 else {
2019 Diag(Loc, diag::err_bad_language);
2020 return 0;
2021 }
2022
2023 // FIXME: Add all the various semantics of linkage specifications
2024 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
2025}
2026