blob: f5d8f6b5e12ad87e0a66c958a1764f850e595d2e [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/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.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;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000111 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 Gregor61366e92008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000144 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146
Chris Lattner3d1cee32008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor61366e92008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor72b505b2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor61366e92008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattner3d1cee32008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 bool Invalid = false;
208
Chris Lattner3d1cee32008-04-08 05:04:30 +0000209 // C++ [dcl.fct.default]p4:
210 //
211 // For non-template functions, default arguments can be added in
212 // later declarations of a function in the same
213 // scope. Declarations in different scopes have completely
214 // distinct sets of default arguments. That is, declarations in
215 // inner scopes do not acquire default arguments from
216 // declarations in outer scopes, and vice versa. In a given
217 // function declaration, all parameters subsequent to a
218 // parameter with a default argument shall have default
219 // arguments supplied in this or previous declarations. A
220 // default argument shall not be redefined by a later
221 // declaration (not even to the same value).
222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223 ParmVarDecl *OldParam = Old->getParamDecl(p);
224 ParmVarDecl *NewParam = New->getParamDecl(p);
225
226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000232 } else if (OldParam->getDefaultArg()) {
233 // Merge the old default argument into the new parameter
234 NewParam->setDefaultArg(OldParam->getDefaultArg());
235 }
236 }
237
Douglas Gregorcda9c672009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245 unsigned NumParams = FD->getNumParams();
246 unsigned p;
247
248 // Find first parameter with a default argument
249 for (p = 0; p < NumParams; ++p) {
250 ParmVarDecl *Param = FD->getParamDecl(p);
251 if (Param->getDefaultArg())
252 break;
253 }
254
255 // C++ [dcl.fct.default]p4:
256 // In a given function declaration, all parameters
257 // subsequent to a parameter with a default argument shall
258 // have default arguments supplied in this or previous
259 // declarations. A default argument shall not be redefined
260 // by a later declaration (not even to the same value).
261 unsigned LastMissingDefaultArg = 0;
262 for(; p < NumParams; ++p) {
263 ParmVarDecl *Param = FD->getParamDecl(p);
264 if (!Param->getDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000271 else
272 Diag(Param->getLocation(),
273 diag::err_param_default_argument_missing);
274
275 LastMissingDefaultArg = p;
276 }
277 }
278
279 if (LastMissingDefaultArg > 0) {
280 // Some default arguments were missing. Clear out all of the
281 // default arguments up to (and including) the last missing
282 // default argument, so that we leave the function parameters
283 // in a semantically valid state.
284 for (p = 0; p <= LastMissingDefaultArg; ++p) {
285 ParmVarDecl *Param = FD->getParamDecl(p);
286 if (Param->getDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000294
Douglas Gregorb48fe382008-10-31 09:07:45 +0000295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000301 CXXRecordDecl *CurDecl;
302 if (SS) {
303 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305 } else
306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregor2943aed2009-03-03 04:44:36 +0000314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320 SourceRange SpecifierRange,
321 bool Virtual, AccessSpecifier Access,
322 QualType BaseType,
323 SourceLocation BaseLoc) {
324 // C++ [class.union]p1:
325 // A union shall not have base classes.
326 if (Class->isUnion()) {
327 Diag(Class->getLocation(), diag::err_base_clause_on_union)
328 << SpecifierRange;
329 return 0;
330 }
331
332 if (BaseType->isDependentType())
333 return new CXXBaseSpecifier(SpecifierRange, Virtual,
334 Class->getTagKind() == RecordDecl::TK_class,
335 Access, BaseType);
336
337 // Base specifiers must be record types.
338 if (!BaseType->isRecordType()) {
339 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340 return 0;
341 }
342
343 // C++ [class.union]p1:
344 // A union shall not be used as a base class.
345 if (BaseType->isUnionType()) {
346 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347 return 0;
348 }
349
350 // C++ [class.derived]p2:
351 // The class-name in a base-specifier shall not be an incompletely
352 // defined class.
Douglas Gregor86447ec2009-03-09 16:13:40 +0000353 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor26dce442009-03-10 00:06:19 +0000354 SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000355 return 0;
356
357 // If the base class is polymorphic, the new one is, too.
358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359 assert(BaseDecl && "Record type has no declaration");
360 BaseDecl = BaseDecl->getDefinition(Context);
361 assert(BaseDecl && "Base type is not incomplete, but has no definition");
362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363 Class->setPolymorphic(true);
364
365 // C++ [dcl.init.aggr]p1:
366 // An aggregate is [...] a class with [...] no base classes [...].
367 Class->setAggregate(false);
368 Class->setPOD(false);
369
370 // Create the base specifier.
371 // FIXME: Allocate via ASTContext?
372 return new CXXBaseSpecifier(SpecifierRange, Virtual,
373 Class->getTagKind() == RecordDecl::TK_class,
374 Access, BaseType);
375}
376
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380/// class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384 bool Virtual, AccessSpecifier Access,
385 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor40808ce2009-03-09 23:48:35 +0000386 AdjustDeclIfTemplate(classdecl);
387 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000388 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000389 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390 Virtual, Access,
391 BaseType, BaseLoc))
392 return BaseSpec;
393
394 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000395}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000396
Douglas Gregor2943aed2009-03-03 04:44:36 +0000397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400 unsigned NumBases) {
401 if (NumBases == 0)
402 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000403
404 // Used to keep track of which base types we have already seen, so
405 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000406 // that the key is always the unqualified canonical type of the base
407 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000408 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000411 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000412 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000413 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000414 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000415 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000416 NewBaseType = NewBaseType.getUnqualifiedType();
417
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000418 if (KnownBaseTypes[NewBaseType]) {
419 // C++ [class.mi]p3:
420 // A class shall not be specified as a direct base class of a
421 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000422 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000423 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000424 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000425 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000426
427 // Delete the duplicate base class specifier; we're going to
428 // overwrite its pointer later.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429 delete Bases[idx];
430
431 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000432 } else {
433 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000434 KnownBaseTypes[NewBaseType] = Bases[idx];
435 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000436 }
437 }
438
439 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000440 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000441
442 // Delete the remaining (good) base class specifiers, since their
443 // data has been copied into the CXXRecordDecl.
444 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2943aed2009-03-03 04:44:36 +0000445 delete Bases[idx];
446
447 return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454 unsigned NumBases) {
455 if (!ClassDecl || !Bases || !NumBases)
456 return;
457
458 AdjustDeclIfTemplate(ClassDecl);
459 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000461}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000462
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474 ExprTy *BW, ExprTy *InitExpr,
475 DeclTy *LastInGroup) {
476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000477 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000478 Expr *BitWidth = static_cast<Expr*>(BW);
479 Expr *Init = static_cast<Expr*>(InitExpr);
480 SourceLocation Loc = D.getIdentifierLoc();
481
Sebastian Redl669d5d72008-11-14 23:42:31 +0000482 bool isFunc = D.isFunctionDeclarator();
483
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000484 // C++ 9.2p6: A member shall not be declared to have automatic storage
485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487 // data members and cannot be applied to names declared const or static,
488 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000489 switch (DS.getStorageClassSpec()) {
490 case DeclSpec::SCS_unspecified:
491 case DeclSpec::SCS_typedef:
492 case DeclSpec::SCS_static:
493 // FALL THROUGH.
494 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000495 case DeclSpec::SCS_mutable:
496 if (isFunc) {
497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000499 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
Sebastian Redla11f42f2008-11-17 23:24:37 +0000502 // FIXME: It would be nicer if the keyword was ignored only for this
503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000504 D.getMutableDeclSpec().ClearStorageClassSpecs();
505 } else {
506 QualType T = GetTypeForDeclarator(D, S);
507 diag::kind err = static_cast<diag::kind>(0);
508 if (T->isReferenceType())
509 err = diag::err_mutable_reference;
510 else if (T.isConstQualified())
511 err = diag::err_mutable_const;
512 if (err != 0) {
513 if (DS.getStorageClassSpecLoc().isValid())
514 Diag(DS.getStorageClassSpecLoc(), err);
515 else
516 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000517 // FIXME: It would be nicer if the keyword was ignored only for this
518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000519 D.getMutableDeclSpec().ClearStorageClassSpecs();
520 }
521 }
522 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000523 default:
524 if (DS.getStorageClassSpecLoc().isValid())
525 Diag(DS.getStorageClassSpecLoc(),
526 diag::err_storageclass_invalid_for_member);
527 else
528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529 D.getMutableDeclSpec().ClearStorageClassSpecs();
530 }
531
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000532 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000533 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000534 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000535 // Check also for this case:
536 //
537 // typedef int f();
538 // f a;
539 //
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000540 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000542 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000543
Sebastian Redl669d5d72008-11-14 23:42:31 +0000544 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000546 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000547
548 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000549 if (isInstField) {
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
551 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000552 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000553 } else {
Daniel Dunbar914701e2008-08-05 16:28:08 +0000554 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattner6f8ce142009-03-05 23:03:49 +0000555 if (!Member) {
556 if (BitWidth) DeleteExpr(BitWidth);
557 return LastInGroup;
558 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000559
560 // Non-instance-fields can't have a bitfield.
561 if (BitWidth) {
562 if (Member->isInvalidDecl()) {
563 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000564 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000565 // C++ 9.6p3: A bit-field shall not be a static member.
566 // "static member 'A' cannot be a bit-field"
567 Diag(Loc, diag::err_static_not_bitfield)
568 << Name << BitWidth->getSourceRange();
569 } else if (isa<TypedefDecl>(Member)) {
570 // "typedef member 'x' cannot be a bit-field"
571 Diag(Loc, diag::err_typedef_not_bitfield)
572 << Name << BitWidth->getSourceRange();
573 } else {
574 // A function typedef ("typedef int f(); f a;").
575 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
576 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000577 << Name << cast<ValueDecl>(Member)->getType()
578 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000579 }
580
581 DeleteExpr(BitWidth);
582 BitWidth = 0;
583 Member->setInvalidDecl();
584 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000585
586 Member->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000587 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000588
Douglas Gregor10bd3682008-11-17 22:58:34 +0000589 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000590
Douglas Gregor021c3b32009-03-11 23:00:04 +0000591 if (Init)
592 AddInitializerToDecl(Member, ExprArg(*this, Init), false);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000593
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000594 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000595 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000596 return LastInGroup;
597 }
598 return Member;
599}
600
Douglas Gregor7ad83902008-11-05 04:29:56 +0000601/// ActOnMemInitializer - Handle a C++ member initializer.
602Sema::MemInitResult
603Sema::ActOnMemInitializer(DeclTy *ConstructorD,
604 Scope *S,
605 IdentifierInfo *MemberOrBase,
606 SourceLocation IdLoc,
607 SourceLocation LParenLoc,
608 ExprTy **Args, unsigned NumArgs,
609 SourceLocation *CommaLocs,
610 SourceLocation RParenLoc) {
611 CXXConstructorDecl *Constructor
612 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
613 if (!Constructor) {
614 // The user wrote a constructor initializer on a function that is
615 // not a C++ constructor. Ignore the error for now, because we may
616 // have more member initializers coming; we'll diagnose it just
617 // once in ActOnMemInitializers.
618 return true;
619 }
620
621 CXXRecordDecl *ClassDecl = Constructor->getParent();
622
623 // C++ [class.base.init]p2:
624 // Names in a mem-initializer-id are looked up in the scope of the
625 // constructor’s class and, if not found in that scope, are looked
626 // up in the scope containing the constructor’s
627 // definition. [Note: if the constructor’s class contains a member
628 // with the same name as a direct or virtual base class of the
629 // class, a mem-initializer-id naming the member or base class and
630 // composed of a single identifier refers to the class member. A
631 // mem-initializer-id for the hidden base class may be specified
632 // using a qualified name. ]
633 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000634 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000635 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000636 if (Result.first != Result.second)
637 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000638
639 // FIXME: Handle members of an anonymous union.
640
641 if (Member) {
642 // FIXME: Perform direct initialization of the member.
643 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
644 }
645
646 // It didn't name a member, so see if it names a class.
Douglas Gregorb696ea32009-02-04 17:00:24 +0000647 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000648 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000649 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
650 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000651
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000652 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000653 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000654 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000655 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000656
657 // C++ [class.base.init]p2:
658 // [...] Unless the mem-initializer-id names a nonstatic data
659 // member of the constructor’s class or a direct or virtual base
660 // of that class, the mem-initializer is ill-formed. A
661 // mem-initializer-list can initialize a base class using any
662 // name that denotes that base class type.
663
664 // First, check for a direct base class.
665 const CXXBaseSpecifier *DirectBaseSpec = 0;
666 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
667 Base != ClassDecl->bases_end(); ++Base) {
668 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
669 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
670 // We found a direct base of this type. That's what we're
671 // initializing.
672 DirectBaseSpec = &*Base;
673 break;
674 }
675 }
676
677 // Check for a virtual base class.
678 // FIXME: We might be able to short-circuit this if we know in
679 // advance that there are no virtual bases.
680 const CXXBaseSpecifier *VirtualBaseSpec = 0;
681 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
682 // We haven't found a base yet; search the class hierarchy for a
683 // virtual base class.
684 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
685 /*DetectVirtual=*/false);
686 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
687 for (BasePaths::paths_iterator Path = Paths.begin();
688 Path != Paths.end(); ++Path) {
689 if (Path->back().Base->isVirtual()) {
690 VirtualBaseSpec = Path->back().Base;
691 break;
692 }
693 }
694 }
695 }
696
697 // C++ [base.class.init]p2:
698 // If a mem-initializer-id is ambiguous because it designates both
699 // a direct non-virtual base class and an inherited virtual base
700 // class, the mem-initializer is ill-formed.
701 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000702 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
703 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000704
705 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
706}
707
708
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000709void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
710 DeclTy *TagDecl,
711 SourceLocation LBrac,
712 SourceLocation RBrac) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000713 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000714 ActOnFields(S, RLoc, TagDecl,
715 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000716 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000717
718 if (!Template)
719 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000720}
721
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000722/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
723/// special functions, such as the default constructor, copy
724/// constructor, or destructor, to the given C++ class (C++
725/// [special]p1). This routine can only be executed just before the
726/// definition of the class is complete.
727void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000728 QualType ClassType = Context.getTypeDeclType(ClassDecl);
729 ClassType = Context.getCanonicalType(ClassType);
730
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000731 if (!ClassDecl->hasUserDeclaredConstructor()) {
732 // C++ [class.ctor]p5:
733 // A default constructor for a class X is a constructor of class X
734 // that can be called without an argument. If there is no
735 // user-declared constructor for class X, a default constructor is
736 // implicitly declared. An implicitly-declared default constructor
737 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000738 DeclarationName Name
739 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000740 CXXConstructorDecl *DefaultCon =
741 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000742 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000743 Context.getFunctionType(Context.VoidTy,
744 0, 0, false, 0),
745 /*isExplicit=*/false,
746 /*isInline=*/true,
747 /*isImplicitlyDeclared=*/true);
748 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000749 DefaultCon->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000750 ClassDecl->addDecl(DefaultCon);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000751
752 // Notify the class that we've added a constructor.
753 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000754 }
755
756 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
757 // C++ [class.copy]p4:
758 // If the class definition does not explicitly declare a copy
759 // constructor, one is declared implicitly.
760
761 // C++ [class.copy]p5:
762 // The implicitly-declared copy constructor for a class X will
763 // have the form
764 //
765 // X::X(const X&)
766 //
767 // if
768 bool HasConstCopyConstructor = true;
769
770 // -- each direct or virtual base class B of X has a copy
771 // constructor whose first parameter is of type const B& or
772 // const volatile B&, and
773 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
774 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
775 const CXXRecordDecl *BaseClassDecl
776 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
777 HasConstCopyConstructor
778 = BaseClassDecl->hasConstCopyConstructor(Context);
779 }
780
781 // -- for all the nonstatic data members of X that are of a
782 // class type M (or array thereof), each such class type
783 // has a copy constructor whose first parameter is of type
784 // const M& or const volatile M&.
785 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
786 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
787 QualType FieldType = (*Field)->getType();
788 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
789 FieldType = Array->getElementType();
790 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
791 const CXXRecordDecl *FieldClassDecl
792 = cast<CXXRecordDecl>(FieldClassType->getDecl());
793 HasConstCopyConstructor
794 = FieldClassDecl->hasConstCopyConstructor(Context);
795 }
796 }
797
Sebastian Redl64b45f72009-01-05 20:52:13 +0000798 // Otherwise, the implicitly declared copy constructor will have
799 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000800 //
801 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +0000802 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000803 if (HasConstCopyConstructor)
804 ArgType = ArgType.withConst();
805 ArgType = Context.getReferenceType(ArgType);
806
Sebastian Redl64b45f72009-01-05 20:52:13 +0000807 // An implicitly-declared copy constructor is an inline public
808 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000809 DeclarationName Name
810 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000811 CXXConstructorDecl *CopyConstructor
812 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000813 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000814 Context.getFunctionType(Context.VoidTy,
815 &ArgType, 1,
816 false, 0),
817 /*isExplicit=*/false,
818 /*isInline=*/true,
819 /*isImplicitlyDeclared=*/true);
820 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000821 CopyConstructor->setImplicit();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000822
823 // Add the parameter to the constructor.
824 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
825 ClassDecl->getLocation(),
826 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000827 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000828 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000829
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000830 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor482b77d2009-01-12 23:27:07 +0000831 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000832 }
833
Sebastian Redl64b45f72009-01-05 20:52:13 +0000834 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
835 // Note: The following rules are largely analoguous to the copy
836 // constructor rules. Note that virtual bases are not taken into account
837 // for determining the argument type of the operator. Note also that
838 // operators taking an object instead of a reference are allowed.
839 //
840 // C++ [class.copy]p10:
841 // If the class definition does not explicitly declare a copy
842 // assignment operator, one is declared implicitly.
843 // The implicitly-defined copy assignment operator for a class X
844 // will have the form
845 //
846 // X& X::operator=(const X&)
847 //
848 // if
849 bool HasConstCopyAssignment = true;
850
851 // -- each direct base class B of X has a copy assignment operator
852 // whose parameter is of type const B&, const volatile B& or B,
853 // and
854 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
855 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
856 const CXXRecordDecl *BaseClassDecl
857 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
858 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
859 }
860
861 // -- for all the nonstatic data members of X that are of a class
862 // type M (or array thereof), each such class type has a copy
863 // assignment operator whose parameter is of type const M&,
864 // const volatile M& or M.
865 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
866 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
867 QualType FieldType = (*Field)->getType();
868 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
869 FieldType = Array->getElementType();
870 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
871 const CXXRecordDecl *FieldClassDecl
872 = cast<CXXRecordDecl>(FieldClassType->getDecl());
873 HasConstCopyAssignment
874 = FieldClassDecl->hasConstCopyAssignment(Context);
875 }
876 }
877
878 // Otherwise, the implicitly declared copy assignment operator will
879 // have the form
880 //
881 // X& X::operator=(X&)
882 QualType ArgType = ClassType;
883 QualType RetType = Context.getReferenceType(ArgType);
884 if (HasConstCopyAssignment)
885 ArgType = ArgType.withConst();
886 ArgType = Context.getReferenceType(ArgType);
887
888 // An implicitly-declared copy assignment operator is an inline public
889 // member of its class.
890 DeclarationName Name =
891 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
892 CXXMethodDecl *CopyAssignment =
893 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
894 Context.getFunctionType(RetType, &ArgType, 1,
895 false, 0),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000896 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000897 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000898 CopyAssignment->setImplicit();
Sebastian Redl64b45f72009-01-05 20:52:13 +0000899
900 // Add the parameter to the operator.
901 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
902 ClassDecl->getLocation(),
903 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000904 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000905 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000906
907 // Don't call addedAssignmentOperator. There is no way to distinguish an
908 // implicit from an explicit assignment operator.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000909 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000910 }
911
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000912 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000913 // C++ [class.dtor]p2:
914 // If a class has no user-declared destructor, a destructor is
915 // declared implicitly. An implicitly-declared destructor is an
916 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000917 DeclarationName Name
918 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000919 CXXDestructorDecl *Destructor
920 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000921 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000922 Context.getFunctionType(Context.VoidTy,
923 0, 0, false, 0),
924 /*isInline=*/true,
925 /*isImplicitlyDeclared=*/true);
926 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000927 Destructor->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000928 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000929 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000930}
931
Douglas Gregor72b505b2008-12-16 21:30:33 +0000932/// ActOnStartDelayedCXXMethodDeclaration - We have completed
933/// parsing a top-level (non-nested) C++ class, and we are now
934/// parsing those parts of the given Method declaration that could
935/// not be parsed earlier (C++ [class.mem]p2), such as default
936/// arguments. This action should enter the scope of the given
937/// Method declaration as if we had just parsed the qualified method
938/// name. However, it should not bring the parameters into scope;
939/// that will be performed by ActOnDelayedCXXMethodParameter.
940void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
941 CXXScopeSpec SS;
942 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
943 ActOnCXXEnterDeclaratorScope(S, SS);
944}
945
946/// ActOnDelayedCXXMethodParameter - We've already started a delayed
947/// C++ method declaration. We're (re-)introducing the given
948/// function parameter into scope for use in parsing later parts of
949/// the method declaration. For example, we could see an
950/// ActOnParamDefaultArgument event for this parameter.
951void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
952 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +0000953
954 // If this parameter has an unparsed default argument, clear it out
955 // to make way for the parsed default argument.
956 if (Param->hasUnparsedDefaultArg())
957 Param->setDefaultArg(0);
958
Douglas Gregor72b505b2008-12-16 21:30:33 +0000959 S->AddDecl(Param);
960 if (Param->getDeclName())
961 IdResolver.AddDecl(Param);
962}
963
964/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
965/// processing the delayed method declaration for Method. The method
966/// declaration is now considered finished. There may be a separate
967/// ActOnStartOfFunctionDef action later (not necessarily
968/// immediately!) for this method, if it was also defined inside the
969/// class body.
970void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
971 FunctionDecl *Method = (FunctionDecl*)MethodD;
972 CXXScopeSpec SS;
973 SS.setScopeRep(Method->getDeclContext());
974 ActOnCXXExitDeclaratorScope(S, SS);
975
976 // Now that we have our default arguments, check the constructor
977 // again. It could produce additional diagnostics or affect whether
978 // the class has implicitly-declared destructors, among other
979 // things.
980 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
981 if (CheckConstructor(Constructor))
982 Constructor->setInvalidDecl();
983 }
984
985 // Check the default arguments, which we may have added.
986 if (!Method->isInvalidDecl())
987 CheckCXXDefaultArguments(Method);
988}
989
Douglas Gregor42a552f2008-11-05 20:51:48 +0000990/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +0000991/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +0000992/// R. If there are any errors in the declarator, this routine will
993/// emit diagnostics and return true. Otherwise, it will return
994/// false. Either way, the type @p R will be updated to reflect a
995/// well-formed type for the constructor.
996bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
997 FunctionDecl::StorageClass& SC) {
998 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
999 bool isInvalid = false;
1000
1001 // C++ [class.ctor]p3:
1002 // A constructor shall not be virtual (10.3) or static (9.4). A
1003 // constructor can be invoked for a const, volatile or const
1004 // volatile object. A constructor shall not be declared const,
1005 // volatile, or const volatile (9.3.2).
1006 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001007 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1008 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1009 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001010 isInvalid = true;
1011 }
1012 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001013 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1014 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1015 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001016 isInvalid = true;
1017 SC = FunctionDecl::None;
1018 }
1019 if (D.getDeclSpec().hasTypeSpecifier()) {
1020 // Constructors don't have return types, but the parser will
1021 // happily parse something like:
1022 //
1023 // class X {
1024 // float X(float);
1025 // };
1026 //
1027 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001028 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1029 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1030 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001031 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001032 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001033 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1034 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001035 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1036 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001037 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001038 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1039 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001040 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001041 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1042 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001043 }
1044
1045 // Rebuild the function type "R" without any type qualifiers (in
1046 // case any of the errors above fired) and with "void" as the
1047 // return type, since constructors don't have return types. We
1048 // *always* have to do this, because GetTypeForDeclarator will
1049 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001050 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001051 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1052 Proto->getNumArgs(),
1053 Proto->isVariadic(),
1054 0);
1055
1056 return isInvalid;
1057}
1058
Douglas Gregor72b505b2008-12-16 21:30:33 +00001059/// CheckConstructor - Checks a fully-formed constructor for
1060/// well-formedness, issuing any diagnostics required. Returns true if
1061/// the constructor declarator is invalid.
1062bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1063 if (Constructor->isInvalidDecl())
1064 return true;
1065
1066 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1067 bool Invalid = false;
1068
1069 // C++ [class.copy]p3:
1070 // A declaration of a constructor for a class X is ill-formed if
1071 // its first parameter is of type (optionally cv-qualified) X and
1072 // either there are no other parameters or else all other
1073 // parameters have default arguments.
1074 if ((Constructor->getNumParams() == 1) ||
1075 (Constructor->getNumParams() > 1 &&
1076 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1077 QualType ParamType = Constructor->getParamDecl(0)->getType();
1078 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1079 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1080 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1081 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1082 Invalid = true;
1083 }
1084 }
1085
1086 // Notify the class that we've added a constructor.
1087 ClassDecl->addedConstructor(Context, Constructor);
1088
1089 return Invalid;
1090}
1091
Douglas Gregor42a552f2008-11-05 20:51:48 +00001092/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1093/// the well-formednes of the destructor declarator @p D with type @p
1094/// R. If there are any errors in the declarator, this routine will
1095/// emit diagnostics and return true. Otherwise, it will return
1096/// false. Either way, the type @p R will be updated to reflect a
1097/// well-formed type for the destructor.
1098bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1099 FunctionDecl::StorageClass& SC) {
1100 bool isInvalid = false;
1101
1102 // C++ [class.dtor]p1:
1103 // [...] A typedef-name that names a class is a class-name
1104 // (7.1.3); however, a typedef-name that names a class shall not
1105 // be used as the identifier in the declarator for a destructor
1106 // declaration.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001107 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1108 if (DeclaratorType->getAsTypedefType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001109 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001110 << DeclaratorType;
Douglas Gregor55c60952008-11-10 14:41:22 +00001111 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001112 }
1113
1114 // C++ [class.dtor]p2:
1115 // A destructor is used to destroy objects of its class type. A
1116 // destructor takes no parameters, and no return type can be
1117 // specified for it (not even void). The address of a destructor
1118 // shall not be taken. A destructor shall not be static. A
1119 // destructor can be invoked for a const, volatile or const
1120 // volatile object. A destructor shall not be declared const,
1121 // volatile or const volatile (9.3.2).
1122 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001123 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1124 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1125 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001126 isInvalid = true;
1127 SC = FunctionDecl::None;
1128 }
1129 if (D.getDeclSpec().hasTypeSpecifier()) {
1130 // Destructors don't have return types, but the parser will
1131 // happily parse something like:
1132 //
1133 // class X {
1134 // float ~X();
1135 // };
1136 //
1137 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001138 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1139 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1140 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001141 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001142 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001143 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1144 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001145 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1146 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001147 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001148 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1149 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001150 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001151 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1152 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001153 }
1154
1155 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001156 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001157 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1158
1159 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001160 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001161 }
1162
1163 // Make sure the destructor isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001164 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor42a552f2008-11-05 20:51:48 +00001165 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1166
1167 // Rebuild the function type "R" without any type qualifiers or
1168 // parameters (in case any of the errors above fired) and with
1169 // "void" as the return type, since destructors don't have return
1170 // types. We *always* have to do this, because GetTypeForDeclarator
1171 // will put in a result type of "int" when none was specified.
1172 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1173
1174 return isInvalid;
1175}
1176
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001177/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1178/// well-formednes of the conversion function declarator @p D with
1179/// type @p R. If there are any errors in the declarator, this routine
1180/// will emit diagnostics and return true. Otherwise, it will return
1181/// false. Either way, the type @p R will be updated to reflect a
1182/// well-formed type for the conversion operator.
1183bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1184 FunctionDecl::StorageClass& SC) {
1185 bool isInvalid = false;
1186
1187 // C++ [class.conv.fct]p1:
1188 // Neither parameter types nor return type can be specified. The
1189 // type of a conversion function (8.3.5) is “function taking no
1190 // parameter returning conversion-type-id.”
1191 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001192 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1193 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1194 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001195 isInvalid = true;
1196 SC = FunctionDecl::None;
1197 }
1198 if (D.getDeclSpec().hasTypeSpecifier()) {
1199 // Conversion functions don't have return types, but the parser will
1200 // happily parse something like:
1201 //
1202 // class X {
1203 // float operator bool();
1204 // };
1205 //
1206 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001207 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1208 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1209 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001210 }
1211
1212 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001213 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001214 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1215
1216 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001217 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001218 }
1219
1220 // Make sure the conversion function isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001221 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001222 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1223
1224 // C++ [class.conv.fct]p4:
1225 // The conversion-type-id shall not represent a function type nor
1226 // an array type.
1227 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1228 if (ConvType->isArrayType()) {
1229 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1230 ConvType = Context.getPointerType(ConvType);
1231 } else if (ConvType->isFunctionType()) {
1232 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1233 ConvType = Context.getPointerType(ConvType);
1234 }
1235
1236 // Rebuild the function type "R" without any parameters (in case any
1237 // of the errors above fired) and with the conversion type as the
1238 // return type.
1239 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00001240 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001241
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001242 // C++0x explicit conversion operators.
1243 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1244 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1245 diag::warn_explicit_conversion_functions)
1246 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1247
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001248 return isInvalid;
1249}
1250
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001251/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1252/// the declaration of the given C++ conversion function. This routine
1253/// is responsible for recording the conversion function in the C++
1254/// class, if possible.
1255Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1256 assert(Conversion && "Expected to receive a conversion function declaration");
1257
Douglas Gregor9d350972008-12-12 08:25:50 +00001258 // Set the lexical context of this conversion function
1259 Conversion->setLexicalDeclContext(CurContext);
1260
1261 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001262
1263 // Make sure we aren't redeclaring the conversion function.
1264 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001265
1266 // C++ [class.conv.fct]p1:
1267 // [...] A conversion function is never used to convert a
1268 // (possibly cv-qualified) object to the (possibly cv-qualified)
1269 // same object type (or a reference to it), to a (possibly
1270 // cv-qualified) base class of that type (or a reference to it),
1271 // or to (possibly cv-qualified) void.
1272 // FIXME: Suppress this warning if the conversion function ends up
1273 // being a virtual function that overrides a virtual function in a
1274 // base class.
1275 QualType ClassType
1276 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1277 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1278 ConvType = ConvTypeRef->getPointeeType();
1279 if (ConvType->isRecordType()) {
1280 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1281 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001282 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001283 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001284 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001285 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001286 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001287 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001288 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001289 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001290 }
1291
Douglas Gregor70316a02008-12-26 15:00:45 +00001292 if (Conversion->getPreviousDeclaration()) {
1293 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1294 for (OverloadedFunctionDecl::function_iterator
1295 Conv = Conversions->function_begin(),
1296 ConvEnd = Conversions->function_end();
1297 Conv != ConvEnd; ++Conv) {
1298 if (*Conv == Conversion->getPreviousDeclaration()) {
1299 *Conv = Conversion;
1300 return (DeclTy *)Conversion;
1301 }
1302 }
1303 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1304 } else
1305 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001306
1307 return (DeclTy *)Conversion;
1308}
1309
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001310//===----------------------------------------------------------------------===//
1311// Namespace Handling
1312//===----------------------------------------------------------------------===//
1313
1314/// ActOnStartNamespaceDef - This is called at the start of a namespace
1315/// definition.
1316Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1317 SourceLocation IdentLoc,
1318 IdentifierInfo *II,
1319 SourceLocation LBrace) {
1320 NamespaceDecl *Namespc =
1321 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1322 Namespc->setLBracLoc(LBrace);
1323
1324 Scope *DeclRegionScope = NamespcScope->getParent();
1325
1326 if (II) {
1327 // C++ [namespace.def]p2:
1328 // The identifier in an original-namespace-definition shall not have been
1329 // previously defined in the declarative region in which the
1330 // original-namespace-definition appears. The identifier in an
1331 // original-namespace-definition is the name of the namespace. Subsequently
1332 // in that declarative region, it is treated as an original-namespace-name.
1333
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001334 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1335 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001336
1337 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1338 // This is an extended namespace definition.
1339 // Attach this namespace decl to the chain of extended namespace
1340 // definitions.
1341 OrigNS->setNextNamespace(Namespc);
1342 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001343
Douglas Gregor44b43212008-12-11 16:49:14 +00001344 // Remove the previous declaration from the scope.
1345 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001346 IdResolver.RemoveDecl(OrigNS);
1347 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001348 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001349 } else if (PrevDecl) {
1350 // This is an invalid name redefinition.
1351 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1352 << Namespc->getDeclName();
1353 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1354 Namespc->setInvalidDecl();
1355 // Continue on to push Namespc as current DeclContext and return it.
1356 }
1357
1358 PushOnScopeChains(Namespc, DeclRegionScope);
1359 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001360 // FIXME: Handle anonymous namespaces
1361 }
1362
1363 // Although we could have an invalid decl (i.e. the namespace name is a
1364 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001365 // FIXME: We should be able to push Namespc here, so that the
1366 // each DeclContext for the namespace has the declarations
1367 // that showed up in that particular namespace definition.
1368 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001369 return Namespc;
1370}
1371
1372/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1373/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1374void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1375 Decl *Dcl = static_cast<Decl *>(D);
1376 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1377 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1378 Namespc->setRBracLoc(RBrace);
1379 PopDeclContext();
1380}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001381
Douglas Gregorf780abc2008-12-30 03:27:21 +00001382Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1383 SourceLocation UsingLoc,
1384 SourceLocation NamespcLoc,
1385 const CXXScopeSpec &SS,
1386 SourceLocation IdentLoc,
1387 IdentifierInfo *NamespcName,
1388 AttributeList *AttrList) {
1389 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1390 assert(NamespcName && "Invalid NamespcName.");
1391 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001392 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00001393
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001394 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00001395
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001396 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001397 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1398 LookupNamespaceName, false);
1399 if (R.isAmbiguous()) {
1400 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1401 return 0;
1402 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001403 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001404 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001405 // C++ [namespace.udir]p1:
1406 // A using-directive specifies that the names in the nominated
1407 // namespace can be used in the scope in which the
1408 // using-directive appears after the using-directive. During
1409 // unqualified name lookup (3.4.1), the names appear as if they
1410 // were declared in the nearest enclosing namespace which
1411 // contains both the using-directive and the nominated
1412 // namespace. [Note: in this context, “contains” means “contains
1413 // directly or indirectly”. ]
1414
1415 // Find enclosing context containing both using-directive and
1416 // nominated namespace.
1417 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1418 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1419 CommonAncestor = CommonAncestor->getParent();
1420
1421 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1422 NamespcLoc, IdentLoc,
1423 cast<NamespaceDecl>(NS),
1424 CommonAncestor);
1425 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001426 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001427 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001428 }
1429
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001430 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001431 delete AttrList;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001432 return UDir;
1433}
1434
1435void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1436 // If scope has associated entity, then using directive is at namespace
1437 // or translation unit scope. We add UsingDirectiveDecls, into
1438 // it's lookup structure.
1439 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1440 Ctx->addDecl(UDir);
1441 else
1442 // Otherwise it is block-sope. using-directives will affect lookup
1443 // only to the end of scope.
1444 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001445}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001446
1447/// AddCXXDirectInitializerToDecl - This action is called immediately after
1448/// ActOnDeclarator, when a C++ direct initializer is present.
1449/// e.g: "int x(1);"
1450void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1451 ExprTy **ExprTys, unsigned NumExprs,
1452 SourceLocation *CommaLocs,
1453 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001454 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001455 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001456
1457 // If there is no declaration, there was an error parsing it. Just ignore
1458 // the initializer.
1459 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001460 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek8189cde2009-02-07 01:47:29 +00001461 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001462 return;
1463 }
1464
1465 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1466 if (!VDecl) {
1467 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1468 RealDecl->setInvalidDecl();
1469 return;
1470 }
1471
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001472 // We will treat direct-initialization as a copy-initialization:
1473 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001474 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1475 //
1476 // Clients that want to distinguish between the two forms, can check for
1477 // direct initializer using VarDecl::hasCXXDirectInitializer().
1478 // A major benefit is that clients that don't particularly care about which
1479 // exactly form was it (like the CodeGen) can handle both cases without
1480 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001481
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001482 // C++ 8.5p11:
1483 // The form of initialization (using parentheses or '=') is generally
1484 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001485 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001486 QualType DeclInitType = VDecl->getType();
1487 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1488 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001489
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001490 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001491 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001492 = PerformInitializationByConstructor(DeclInitType,
1493 (Expr **)ExprTys, NumExprs,
1494 VDecl->getLocation(),
1495 SourceRange(VDecl->getLocation(),
1496 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001497 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001498 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001499 if (!Constructor) {
1500 RealDecl->setInvalidDecl();
1501 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001502
1503 // Let clients know that initialization was done with a direct
1504 // initializer.
1505 VDecl->setCXXDirectInitializer(true);
1506
1507 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1508 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001509 return;
1510 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001511
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001512 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001513 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1514 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001515 RealDecl->setInvalidDecl();
1516 return;
1517 }
1518
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001519 // Let clients know that initialization was done with a direct initializer.
1520 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001521
1522 assert(NumExprs == 1 && "Expected 1 expression");
1523 // Set the init expression, handles conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001524 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001525}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001526
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001527/// PerformInitializationByConstructor - Perform initialization by
1528/// constructor (C++ [dcl.init]p14), which may occur as part of
1529/// direct-initialization or copy-initialization. We are initializing
1530/// an object of type @p ClassType with the given arguments @p
1531/// Args. @p Loc is the location in the source code where the
1532/// initializer occurs (e.g., a declaration, member initializer,
1533/// functional cast, etc.) while @p Range covers the whole
1534/// initialization. @p InitEntity is the entity being initialized,
1535/// which may by the name of a declaration or a type. @p Kind is the
1536/// kind of initialization we're performing, which affects whether
1537/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001538/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001539/// when the initialization fails, emits a diagnostic and returns
1540/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001541CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001542Sema::PerformInitializationByConstructor(QualType ClassType,
1543 Expr **Args, unsigned NumArgs,
1544 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001545 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001546 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001547 const RecordType *ClassRec = ClassType->getAsRecordType();
1548 assert(ClassRec && "Can only initialize a class type here");
1549
1550 // C++ [dcl.init]p14:
1551 //
1552 // If the initialization is direct-initialization, or if it is
1553 // copy-initialization where the cv-unqualified version of the
1554 // source type is the same class as, or a derived class of, the
1555 // class of the destination, constructors are considered. The
1556 // applicable constructors are enumerated (13.3.1.3), and the
1557 // best one is chosen through overload resolution (13.3). The
1558 // constructor so selected is called to initialize the object,
1559 // with the initializer expression(s) as its argument(s). If no
1560 // constructor applies, or the overload resolution is ambiguous,
1561 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001562 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1563 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001564
1565 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001566 DeclarationName ConstructorName
1567 = Context.DeclarationNames.getCXXConstructorName(
1568 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001569 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001570 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001571 Con != ConEnd; ++Con) {
1572 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001573 if ((Kind == IK_Direct) ||
1574 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1575 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1576 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1577 }
1578
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001579 // FIXME: When we decide not to synthesize the implicitly-declared
1580 // constructors, we'll need to make them appear here.
1581
Douglas Gregor18fe5682008-11-03 20:45:27 +00001582 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001583 switch (BestViableFunction(CandidateSet, Best)) {
1584 case OR_Success:
1585 // We found a constructor. Return it.
1586 return cast<CXXConstructorDecl>(Best->Function);
1587
1588 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001589 if (InitEntity)
1590 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001591 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00001592 else
1593 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001594 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00001595 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001596 return 0;
1597
1598 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001599 if (InitEntity)
1600 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1601 else
1602 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001603 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1604 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001605
1606 case OR_Deleted:
1607 if (InitEntity)
1608 Diag(Loc, diag::err_ovl_deleted_init)
1609 << Best->Function->isDeleted()
1610 << InitEntity << Range;
1611 else
1612 Diag(Loc, diag::err_ovl_deleted_init)
1613 << Best->Function->isDeleted()
1614 << InitEntity << Range;
1615 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1616 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001617 }
1618
1619 return 0;
1620}
1621
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001622/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1623/// determine whether they are reference-related,
1624/// reference-compatible, reference-compatible with added
1625/// qualification, or incompatible, for use in C++ initialization by
1626/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1627/// type, and the first type (T1) is the pointee type of the reference
1628/// type being initialized.
1629Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001630Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1631 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001632 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1633 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1634
1635 T1 = Context.getCanonicalType(T1);
1636 T2 = Context.getCanonicalType(T2);
1637 QualType UnqualT1 = T1.getUnqualifiedType();
1638 QualType UnqualT2 = T2.getUnqualifiedType();
1639
1640 // C++ [dcl.init.ref]p4:
1641 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1642 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1643 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001644 if (UnqualT1 == UnqualT2)
1645 DerivedToBase = false;
1646 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1647 DerivedToBase = true;
1648 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001649 return Ref_Incompatible;
1650
1651 // At this point, we know that T1 and T2 are reference-related (at
1652 // least).
1653
1654 // C++ [dcl.init.ref]p4:
1655 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1656 // reference-related to T2 and cv1 is the same cv-qualification
1657 // as, or greater cv-qualification than, cv2. For purposes of
1658 // overload resolution, cases for which cv1 is greater
1659 // cv-qualification than cv2 are identified as
1660 // reference-compatible with added qualification (see 13.3.3.2).
1661 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1662 return Ref_Compatible;
1663 else if (T1.isMoreQualifiedThan(T2))
1664 return Ref_Compatible_With_Added_Qualification;
1665 else
1666 return Ref_Related;
1667}
1668
1669/// CheckReferenceInit - Check the initialization of a reference
1670/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1671/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001672/// list), and DeclType is the type of the declaration. When ICS is
1673/// non-null, this routine will compute the implicit conversion
1674/// sequence according to C++ [over.ics.ref] and will not produce any
1675/// diagnostics; when ICS is null, it will emit diagnostics when any
1676/// errors are found. Either way, a return value of true indicates
1677/// that there was a failure, a return value of false indicates that
1678/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001679///
1680/// When @p SuppressUserConversions, user-defined conversions are
1681/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001682/// When @p AllowExplicit, we also permit explicit user-defined
1683/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001684bool
1685Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001686 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001687 bool SuppressUserConversions,
1688 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001689 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1690
1691 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1692 QualType T2 = Init->getType();
1693
Douglas Gregor904eed32008-11-10 20:40:00 +00001694 // If the initializer is the address of an overloaded function, try
1695 // to resolve the overloaded function. If all goes well, T2 is the
1696 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00001697 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00001698 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1699 ICS != 0);
1700 if (Fn) {
1701 // Since we're performing this reference-initialization for
1702 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001703 if (!ICS) {
1704 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1705 return true;
1706
Douglas Gregor904eed32008-11-10 20:40:00 +00001707 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001708 }
Douglas Gregor904eed32008-11-10 20:40:00 +00001709
1710 T2 = Fn->getType();
1711 }
1712 }
1713
Douglas Gregor15da57e2008-10-29 02:00:59 +00001714 // Compute some basic properties of the types and the initializer.
1715 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001716 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001717 ReferenceCompareResult RefRelationship
1718 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1719
1720 // Most paths end in a failed conversion.
1721 if (ICS)
1722 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001723
1724 // C++ [dcl.init.ref]p5:
1725 // A reference to type “cv1 T1” is initialized by an expression
1726 // of type “cv2 T2” as follows:
1727
1728 // -- If the initializer expression
1729
1730 bool BindsDirectly = false;
1731 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1732 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001733 //
1734 // Note that the bit-field check is skipped if we are just computing
1735 // the implicit conversion sequence (C++ [over.best.ics]p2).
1736 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1737 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001738 BindsDirectly = true;
1739
Douglas Gregor15da57e2008-10-29 02:00:59 +00001740 if (ICS) {
1741 // C++ [over.ics.ref]p1:
1742 // When a parameter of reference type binds directly (8.5.3)
1743 // to an argument expression, the implicit conversion sequence
1744 // is the identity conversion, unless the argument expression
1745 // has a type that is a derived class of the parameter type,
1746 // in which case the implicit conversion sequence is a
1747 // derived-to-base Conversion (13.3.3.1).
1748 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1749 ICS->Standard.First = ICK_Identity;
1750 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1751 ICS->Standard.Third = ICK_Identity;
1752 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1753 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001754 ICS->Standard.ReferenceBinding = true;
1755 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001756
1757 // Nothing more to do: the inaccessibility/ambiguity check for
1758 // derived-to-base conversions is suppressed when we're
1759 // computing the implicit conversion sequence (C++
1760 // [over.best.ics]p2).
1761 return false;
1762 } else {
1763 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001764 // FIXME: Binding to a subobject of the lvalue is going to require
1765 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001766 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001767 }
1768 }
1769
1770 // -- has a class type (i.e., T2 is a class type) and can be
1771 // implicitly converted to an lvalue of type “cv3 T3,”
1772 // where “cv1 T1” is reference-compatible with “cv3 T3”
1773 // 92) (this conversion is selected by enumerating the
1774 // applicable conversion functions (13.3.1.6) and choosing
1775 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001776 if (!SuppressUserConversions && T2->isRecordType()) {
1777 // FIXME: Look for conversions in base classes!
1778 CXXRecordDecl *T2RecordDecl
1779 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001780
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001781 OverloadCandidateSet CandidateSet;
1782 OverloadedFunctionDecl *Conversions
1783 = T2RecordDecl->getConversionFunctions();
1784 for (OverloadedFunctionDecl::function_iterator Func
1785 = Conversions->function_begin();
1786 Func != Conversions->function_end(); ++Func) {
1787 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1788
1789 // If the conversion function doesn't return a reference type,
1790 // it can't be considered for this conversion.
1791 // FIXME: This will change when we support rvalue references.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001792 if (Conv->getConversionType()->isReferenceType() &&
1793 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001794 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1795 }
1796
1797 OverloadCandidateSet::iterator Best;
1798 switch (BestViableFunction(CandidateSet, Best)) {
1799 case OR_Success:
1800 // This is a direct binding.
1801 BindsDirectly = true;
1802
1803 if (ICS) {
1804 // C++ [over.ics.ref]p1:
1805 //
1806 // [...] If the parameter binds directly to the result of
1807 // applying a conversion function to the argument
1808 // expression, the implicit conversion sequence is a
1809 // user-defined conversion sequence (13.3.3.1.2), with the
1810 // second standard conversion sequence either an identity
1811 // conversion or, if the conversion function returns an
1812 // entity of a type that is a derived class of the parameter
1813 // type, a derived-to-base Conversion.
1814 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1815 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1816 ICS->UserDefined.After = Best->FinalConversion;
1817 ICS->UserDefined.ConversionFunction = Best->Function;
1818 assert(ICS->UserDefined.After.ReferenceBinding &&
1819 ICS->UserDefined.After.DirectBinding &&
1820 "Expected a direct reference binding!");
1821 return false;
1822 } else {
1823 // Perform the conversion.
1824 // FIXME: Binding to a subobject of the lvalue is going to require
1825 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001826 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001827 }
1828 break;
1829
1830 case OR_Ambiguous:
1831 assert(false && "Ambiguous reference binding conversions not implemented.");
1832 return true;
1833
1834 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001835 case OR_Deleted:
1836 // There was no suitable conversion, or we found a deleted
1837 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001838 break;
1839 }
1840 }
1841
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001842 if (BindsDirectly) {
1843 // C++ [dcl.init.ref]p4:
1844 // [...] In all cases where the reference-related or
1845 // reference-compatible relationship of two types is used to
1846 // establish the validity of a reference binding, and T1 is a
1847 // base class of T2, a program that necessitates such a binding
1848 // is ill-formed if T1 is an inaccessible (clause 11) or
1849 // ambiguous (10.2) base class of T2.
1850 //
1851 // Note that we only check this condition when we're allowed to
1852 // complain about errors, because we should not be checking for
1853 // ambiguity (or inaccessibility) unless the reference binding
1854 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001855 if (DerivedToBase)
1856 return CheckDerivedToBaseConversion(T2, T1,
1857 Init->getSourceRange().getBegin(),
1858 Init->getSourceRange());
1859 else
1860 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001861 }
1862
1863 // -- Otherwise, the reference shall be to a non-volatile const
1864 // type (i.e., cv1 shall be const).
1865 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001866 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001867 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001868 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001869 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1870 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001871 return true;
1872 }
1873
1874 // -- If the initializer expression is an rvalue, with T2 a
1875 // class type, and “cv1 T1” is reference-compatible with
1876 // “cv2 T2,” the reference is bound in one of the
1877 // following ways (the choice is implementation-defined):
1878 //
1879 // -- The reference is bound to the object represented by
1880 // the rvalue (see 3.10) or to a sub-object within that
1881 // object.
1882 //
1883 // -- A temporary of type “cv1 T2” [sic] is created, and
1884 // a constructor is called to copy the entire rvalue
1885 // object into the temporary. The reference is bound to
1886 // the temporary or to a sub-object within the
1887 // temporary.
1888 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001889 // The constructor that would be used to make the copy
1890 // shall be callable whether or not the copy is actually
1891 // done.
1892 //
1893 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1894 // freedom, so we will always take the first option and never build
1895 // a temporary in this case. FIXME: We will, however, have to check
1896 // for the presence of a copy constructor in C++98/03 mode.
1897 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001898 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1899 if (ICS) {
1900 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1901 ICS->Standard.First = ICK_Identity;
1902 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1903 ICS->Standard.Third = ICK_Identity;
1904 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1905 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001906 ICS->Standard.ReferenceBinding = true;
1907 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001908 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001909 // FIXME: Binding to a subobject of the rvalue is going to require
1910 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001911 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001912 }
1913 return false;
1914 }
1915
1916 // -- Otherwise, a temporary of type “cv1 T1” is created and
1917 // initialized from the initializer expression using the
1918 // rules for a non-reference copy initialization (8.5). The
1919 // reference is then bound to the temporary. If T1 is
1920 // reference-related to T2, cv1 must be the same
1921 // cv-qualification as, or greater cv-qualification than,
1922 // cv2; otherwise, the program is ill-formed.
1923 if (RefRelationship == Ref_Related) {
1924 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1925 // we would be reference-compatible or reference-compatible with
1926 // added qualification. But that wasn't the case, so the reference
1927 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001928 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001929 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001930 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00001931 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1932 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001933 return true;
1934 }
1935
Douglas Gregor734d9862009-01-30 23:27:23 +00001936 // If at least one of the types is a class type, the types are not
1937 // related, and we aren't allowed any user conversions, the
1938 // reference binding fails. This case is important for breaking
1939 // recursion, since TryImplicitConversion below will attempt to
1940 // create a temporary through the use of a copy constructor.
1941 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
1942 (T1->isRecordType() || T2->isRecordType())) {
1943 if (!ICS)
1944 Diag(Init->getSourceRange().getBegin(),
1945 diag::err_typecheck_convert_incompatible)
1946 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
1947 return true;
1948 }
1949
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001950 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001951 if (ICS) {
1952 /// C++ [over.ics.ref]p2:
1953 ///
1954 /// When a parameter of reference type is not bound directly to
1955 /// an argument expression, the conversion sequence is the one
1956 /// required to convert the argument expression to the
1957 /// underlying type of the reference according to
1958 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1959 /// to copy-initializing a temporary of the underlying type with
1960 /// the argument expression. Any difference in top-level
1961 /// cv-qualification is subsumed by the initialization itself
1962 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001963 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001964 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1965 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00001966 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00001967 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001968}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001969
1970/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1971/// of this overloaded operator is well-formed. If so, returns false;
1972/// otherwise, emits appropriate diagnostics and returns true.
1973bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001974 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001975 "Expected an overloaded operator declaration");
1976
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001977 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1978
1979 // C++ [over.oper]p5:
1980 // The allocation and deallocation functions, operator new,
1981 // operator new[], operator delete and operator delete[], are
1982 // described completely in 3.7.3. The attributes and restrictions
1983 // found in the rest of this subclause do not apply to them unless
1984 // explicitly stated in 3.7.3.
1985 // FIXME: Write a separate routine for checking this. For now, just
1986 // allow it.
1987 if (Op == OO_New || Op == OO_Array_New ||
1988 Op == OO_Delete || Op == OO_Array_Delete)
1989 return false;
1990
1991 // C++ [over.oper]p6:
1992 // An operator function shall either be a non-static member
1993 // function or be a non-member function and have at least one
1994 // parameter whose type is a class, a reference to a class, an
1995 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00001996 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
1997 if (MethodDecl->isStatic())
1998 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001999 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002000 } else {
2001 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002002 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2003 ParamEnd = FnDecl->param_end();
2004 Param != ParamEnd; ++Param) {
2005 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002006 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2007 ClassOrEnumParam = true;
2008 break;
2009 }
2010 }
2011
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002012 if (!ClassOrEnumParam)
2013 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002014 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002015 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002016 }
2017
2018 // C++ [over.oper]p8:
2019 // An operator function cannot have default arguments (8.3.6),
2020 // except where explicitly stated below.
2021 //
2022 // Only the function-call operator allows default arguments
2023 // (C++ [over.call]p1).
2024 if (Op != OO_Call) {
2025 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2026 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002027 if ((*Param)->hasUnparsedDefaultArg())
2028 return Diag((*Param)->getLocation(),
2029 diag::err_operator_overload_default_arg)
2030 << FnDecl->getDeclName();
2031 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002032 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002033 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002034 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002035 }
2036 }
2037
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002038 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2039 { false, false, false }
2040#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2041 , { Unary, Binary, MemberOnly }
2042#include "clang/Basic/OperatorKinds.def"
2043 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002044
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002045 bool CanBeUnaryOperator = OperatorUses[Op][0];
2046 bool CanBeBinaryOperator = OperatorUses[Op][1];
2047 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002048
2049 // C++ [over.oper]p8:
2050 // [...] Operator functions cannot have more or fewer parameters
2051 // than the number required for the corresponding operator, as
2052 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002053 unsigned NumParams = FnDecl->getNumParams()
2054 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002055 if (Op != OO_Call &&
2056 ((NumParams == 1 && !CanBeUnaryOperator) ||
2057 (NumParams == 2 && !CanBeBinaryOperator) ||
2058 (NumParams < 1) || (NumParams > 2))) {
2059 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002060 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002061 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002062 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002063 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002064 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002065 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002066 assert(CanBeBinaryOperator &&
2067 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002068 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002069 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002070
Chris Lattner416e46f2008-11-21 07:57:12 +00002071 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002072 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002073 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002074
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002075 // Overloaded operators other than operator() cannot be variadic.
2076 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00002077 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002078 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002079 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002080 }
2081
2082 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002083 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2084 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002085 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002086 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002087 }
2088
2089 // C++ [over.inc]p1:
2090 // The user-defined function called operator++ implements the
2091 // prefix and postfix ++ operator. If this function is a member
2092 // function with no parameters, or a non-member function with one
2093 // parameter of class or enumeration type, it defines the prefix
2094 // increment operator ++ for objects of that type. If the function
2095 // is a member function with one parameter (which shall be of type
2096 // int) or a non-member function with two parameters (the second
2097 // of which shall be of type int), it defines the postfix
2098 // increment operator ++ for objects of that type.
2099 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2100 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2101 bool ParamIsInt = false;
2102 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2103 ParamIsInt = BT->getKind() == BuiltinType::Int;
2104
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002105 if (!ParamIsInt)
2106 return Diag(LastParam->getLocation(),
2107 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002108 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002109 }
2110
Sebastian Redl64b45f72009-01-05 20:52:13 +00002111 // Notify the class if it got an assignment operator.
2112 if (Op == OO_Equal) {
2113 // Would have returned earlier otherwise.
2114 assert(isa<CXXMethodDecl>(FnDecl) &&
2115 "Overloaded = not member, but not filtered.");
2116 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2117 Method->getParent()->addedAssignmentOperator(Context, Method);
2118 }
2119
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002120 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002121}
Chris Lattner5a003a42008-12-17 07:09:26 +00002122
Douglas Gregor074149e2009-01-05 19:45:36 +00002123/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2124/// linkage specification, including the language and (if present)
2125/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2126/// the location of the language string literal, which is provided
2127/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2128/// the '{' brace. Otherwise, this linkage specification does not
2129/// have any braces.
2130Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2131 SourceLocation ExternLoc,
2132 SourceLocation LangLoc,
2133 const char *Lang,
2134 unsigned StrSize,
2135 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002136 LinkageSpecDecl::LanguageIDs Language;
2137 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2138 Language = LinkageSpecDecl::lang_c;
2139 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2140 Language = LinkageSpecDecl::lang_cxx;
2141 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002142 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002143 return 0;
2144 }
2145
2146 // FIXME: Add all the various semantics of linkage specifications
2147
Douglas Gregor074149e2009-01-05 19:45:36 +00002148 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2149 LangLoc, Language,
2150 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002151 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002152 PushDeclContext(S, D);
2153 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002154}
2155
Douglas Gregor074149e2009-01-05 19:45:36 +00002156/// ActOnFinishLinkageSpecification - Completely the definition of
2157/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2158/// valid, it's the position of the closing '}' brace in a linkage
2159/// specification that uses braces.
2160Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2161 DeclTy *LinkageSpec,
2162 SourceLocation RBraceLoc) {
2163 if (LinkageSpec)
2164 PopDeclContext();
2165 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002166}
2167
Sebastian Redl4b07b292008-12-22 19:15:10 +00002168/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2169/// handler.
2170Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2171{
2172 QualType ExDeclType = GetTypeForDeclarator(D, S);
2173 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2174
2175 bool Invalid = false;
2176
2177 // Arrays and functions decay.
2178 if (ExDeclType->isArrayType())
2179 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2180 else if (ExDeclType->isFunctionType())
2181 ExDeclType = Context.getPointerType(ExDeclType);
2182
2183 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2184 // The exception-declaration shall not denote a pointer or reference to an
2185 // incomplete type, other than [cv] void*.
2186 QualType BaseType = ExDeclType;
2187 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002188 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002189 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2190 BaseType = Ptr->getPointeeType();
2191 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002192 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002193 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2194 BaseType = Ref->getPointeeType();
2195 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002196 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002197 }
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002198 if ((Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor86447ec2009-03-09 16:13:40 +00002199 RequireCompleteType(Begin, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00002200 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002201
Sebastian Redl8351da02008-12-22 21:35:02 +00002202 // FIXME: Need to test for ability to copy-construct and destroy the
2203 // exception variable.
2204 // FIXME: Need to check for abstract classes.
2205
Sebastian Redl4b07b292008-12-22 19:15:10 +00002206 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002207 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002208 // The scope should be freshly made just for us. There is just no way
2209 // it contains any previous declaration.
2210 assert(!S->isDeclScope(PrevDecl));
2211 if (PrevDecl->isTemplateParameter()) {
2212 // Maybe we will complain about the shadowed template parameter.
2213 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2214
2215 }
2216 }
2217
2218 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002219 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002220 if (D.getInvalidType() || Invalid)
2221 ExDecl->setInvalidDecl();
2222
2223 if (D.getCXXScopeSpec().isSet()) {
2224 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2225 << D.getCXXScopeSpec().getRange();
2226 ExDecl->setInvalidDecl();
2227 }
2228
2229 // Add the exception declaration into this scope.
2230 S->AddDecl(ExDecl);
2231 if (II)
2232 IdResolver.AddDecl(ExDecl);
2233
2234 ProcessDeclAttributes(ExDecl, D);
2235 return ExDecl;
2236}