blob: 9bf10cece810dca8679dd9ad582688d37a1e2cec [file] [log] [blame]
Chris Lattnerac7b83a2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
77 diag::err_param_default_argument_references_param,
78 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
85 diag::err_param_default_argument_references_local,
86 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
98 diag::err_param_default_argument_references_this,
99 ThisE->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
110 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
115 Diag(EqualLoc, diag::err_param_default_argument,
116 DefaultArg->getSourceRange());
117 return;
118 }
119
120 // C++ [dcl.fct.default]p5
121 // A default argument expression is implicitly converted (clause
122 // 4) to the parameter type. The default argument expression has
123 // the same semantic constraints as the initializer expression in
124 // a declaration of a variable of the parameter type, using the
125 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000126 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor58c428c2008-11-04 13:57:51 +0000127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
128 "in default argument");
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000129 if (DefaultArgPtr != DefaultArg.get()) {
130 DefaultArg.take();
131 DefaultArg.reset(DefaultArgPtr);
132 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000133 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000134 return;
135 }
136
Chris Lattner97316c02008-04-10 02:22:51 +0000137 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000139 if (DefaultArgChecker.Visit(DefaultArg.get()))
140 return;
141
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(DefaultArg.take());
144}
145
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000146/// CheckExtraCXXDefaultArguments - Check for any extra default
147/// arguments in the declarator, which is not a function declaration
148/// or definition and therefore is not permitted to have default
149/// arguments. This routine should be invoked for every declarator
150/// that is not a function declaration or definition.
151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
152 // C++ [dcl.fct.default]p3
153 // A default argument expression shall be specified only in the
154 // parameter-declaration-clause of a function declaration or in a
155 // template-parameter (14.1). It shall not be specified for a
156 // parameter pack. If it is specified in a
157 // parameter-declaration-clause, it shall not occur within a
158 // declarator or abstract-declarator of a parameter-declaration.
159 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
160 DeclaratorChunk &chunk = D.getTypeObject(i);
161 if (chunk.Kind == DeclaratorChunk::Function) {
162 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
163 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
164 if (Param->getDefaultArg()) {
165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
166 Param->getDefaultArg()->getSourceRange());
167 Param->setDefaultArg(0);
168 }
169 }
170 }
171 }
172}
173
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000174// MergeCXXFunctionDecl - Merge two declarations of the same C++
175// function, once we already know that they have the same
176// type. Subroutine of MergeFunctionDecl.
177FunctionDecl *
178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
179 // C++ [dcl.fct.default]p4:
180 //
181 // For non-template functions, default arguments can be added in
182 // later declarations of a function in the same
183 // scope. Declarations in different scopes have completely
184 // distinct sets of default arguments. That is, declarations in
185 // inner scopes do not acquire default arguments from
186 // declarations in outer scopes, and vice versa. In a given
187 // function declaration, all parameters subsequent to a
188 // parameter with a default argument shall have default
189 // arguments supplied in this or previous declarations. A
190 // default argument shall not be redefined by a later
191 // declaration (not even to the same value).
192 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
193 ParmVarDecl *OldParam = Old->getParamDecl(p);
194 ParmVarDecl *NewParam = New->getParamDecl(p);
195
196 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
197 Diag(NewParam->getLocation(),
198 diag::err_param_default_argument_redefinition,
199 NewParam->getDefaultArg()->getSourceRange());
200 Diag(OldParam->getLocation(), diag::err_previous_definition);
201 } else if (OldParam->getDefaultArg()) {
202 // Merge the old default argument into the new parameter
203 NewParam->setDefaultArg(OldParam->getDefaultArg());
204 }
205 }
206
207 return New;
208}
209
210/// CheckCXXDefaultArguments - Verify that the default arguments for a
211/// function declaration are well-formed according to C++
212/// [dcl.fct.default].
213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
214 unsigned NumParams = FD->getNumParams();
215 unsigned p;
216
217 // Find first parameter with a default argument
218 for (p = 0; p < NumParams; ++p) {
219 ParmVarDecl *Param = FD->getParamDecl(p);
220 if (Param->getDefaultArg())
221 break;
222 }
223
224 // C++ [dcl.fct.default]p4:
225 // In a given function declaration, all parameters
226 // subsequent to a parameter with a default argument shall
227 // have default arguments supplied in this or previous
228 // declarations. A default argument shall not be redefined
229 // by a later declaration (not even to the same value).
230 unsigned LastMissingDefaultArg = 0;
231 for(; p < NumParams; ++p) {
232 ParmVarDecl *Param = FD->getParamDecl(p);
233 if (!Param->getDefaultArg()) {
234 if (Param->getIdentifier())
235 Diag(Param->getLocation(),
236 diag::err_param_default_argument_missing_name,
237 Param->getIdentifier()->getName());
238 else
239 Diag(Param->getLocation(),
240 diag::err_param_default_argument_missing);
241
242 LastMissingDefaultArg = p;
243 }
244 }
245
246 if (LastMissingDefaultArg > 0) {
247 // Some default arguments were missing. Clear out all of the
248 // default arguments up to (and including) the last missing
249 // default argument, so that we leave the function parameters
250 // in a semantically valid state.
251 for (p = 0; p <= LastMissingDefaultArg; ++p) {
252 ParmVarDecl *Param = FD->getParamDecl(p);
253 if (Param->getDefaultArg()) {
254 delete Param->getDefaultArg();
255 Param->setDefaultArg(0);
256 }
257 }
258 }
259}
Douglas Gregorec93f442008-04-13 21:30:24 +0000260
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000261/// isCurrentClassName - Determine whether the identifier II is the
262/// name of the class type currently being defined. In the case of
263/// nested classes, this will only return true if II is the name of
264/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
266 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000267 CXXRecordDecl *CurDecl;
268 if (SS) {
269 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
270 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
271 } else
272 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
273
274 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000275 return &II == CurDecl->getIdentifier();
276 else
277 return false;
278}
279
Douglas Gregorec93f442008-04-13 21:30:24 +0000280/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
281/// one entry in the base class list of a class specifier, for
282/// example:
283/// class foo : public bar, virtual private baz {
284/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000285Sema::BaseResult
286Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
287 bool Virtual, AccessSpecifier Access,
288 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000289 RecordDecl *Decl = (RecordDecl*)classdecl;
290 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
291
292 // Base specifiers must be record types.
293 if (!BaseType->isRecordType()) {
294 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000295 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000296 }
297
298 // C++ [class.union]p1:
299 // A union shall not be used as a base class.
300 if (BaseType->isUnionType()) {
301 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000302 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000303 }
304
305 // C++ [class.union]p1:
306 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000307 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000308 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
309 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000310 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000311 }
312
313 // C++ [class.derived]p2:
314 // The class-name in a base-specifier shall not be an incompletely
315 // defined class.
316 if (BaseType->isIncompleteType()) {
317 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000318 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000319 }
320
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000321 // If the base class is polymorphic, the new one is, too.
322 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
323 assert(BaseDecl && "Record type has no declaration");
324 BaseDecl = BaseDecl->getDefinition(Context);
325 assert(BaseDecl && "Base type is not incomplete, but has no definition");
326 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) {
327 cast<CXXRecordDecl>(Decl)->setPolymorphic(true);
328 }
329
Douglas Gregorabed2172008-10-22 17:49:05 +0000330 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000331 return new CXXBaseSpecifier(SpecifierRange, Virtual,
332 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000333}
Douglas Gregorec93f442008-04-13 21:30:24 +0000334
Douglas Gregorabed2172008-10-22 17:49:05 +0000335/// ActOnBaseSpecifiers - Attach the given base specifiers to the
336/// class, after checking whether there are any duplicate base
337/// classes.
338void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
339 unsigned NumBases) {
340 if (NumBases == 0)
341 return;
342
343 // Used to keep track of which base types we have already seen, so
344 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000345 // that the key is always the unqualified canonical type of the base
346 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000347 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
348
349 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000350 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
351 unsigned NumGoodBases = 0;
352 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000353 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000354 = Context.getCanonicalType(BaseSpecs[idx]->getType());
355 NewBaseType = NewBaseType.getUnqualifiedType();
356
Douglas Gregorabed2172008-10-22 17:49:05 +0000357 if (KnownBaseTypes[NewBaseType]) {
358 // C++ [class.mi]p3:
359 // A class shall not be specified as a direct base class of a
360 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000361 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000362 diag::err_duplicate_base_class,
363 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000364 BaseSpecs[idx]->getSourceRange());
365
366 // Delete the duplicate base class specifier; we're going to
367 // overwrite its pointer later.
368 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000369 } else {
370 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000371 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
372 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000373 }
374 }
375
376 // Attach the remaining base class specifiers to the derived class.
377 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000378 Decl->setBases(BaseSpecs, NumGoodBases);
379
380 // Delete the remaining (good) base class specifiers, since their
381 // data has been copied into the CXXRecordDecl.
382 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
383 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000384}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000385
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000386//===----------------------------------------------------------------------===//
387// C++ class member Handling
388//===----------------------------------------------------------------------===//
389
390/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
391/// definition, when on C++.
392void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000393 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
394 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000395 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000396
397 if (Dcl->getIdentifier()) {
398 // C++ [class]p2:
399 // [...] The class-name is also inserted into the scope of the
400 // class itself; this is known as the injected-class-name. For
401 // purposes of access checking, the injected-class-name is treated
402 // as if it were a public member name.
Douglas Gregorbd19fdb2008-11-10 14:41:22 +0000403 PushOnScopeChains(Dcl, S);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000404 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000405}
406
407/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
408/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
409/// bitfield width if there is one and 'InitExpr' specifies the initializer if
410/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
411/// declarators on it.
412///
413/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
414/// an instance field is declared, a new CXXFieldDecl is created but the method
415/// does *not* return it; it returns LastInGroup instead. The other C++ members
416/// (which are all ScopedDecls) are returned after appending them to
417/// LastInGroup.
418Sema::DeclTy *
419Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
420 ExprTy *BW, ExprTy *InitExpr,
421 DeclTy *LastInGroup) {
422 const DeclSpec &DS = D.getDeclSpec();
423 IdentifierInfo *II = D.getIdentifier();
424 Expr *BitWidth = static_cast<Expr*>(BW);
425 Expr *Init = static_cast<Expr*>(InitExpr);
426 SourceLocation Loc = D.getIdentifierLoc();
427
428 // C++ 9.2p6: A member shall not be declared to have automatic storage
429 // duration (auto, register) or with the extern storage-class-specifier.
430 switch (DS.getStorageClassSpec()) {
431 case DeclSpec::SCS_unspecified:
432 case DeclSpec::SCS_typedef:
433 case DeclSpec::SCS_static:
434 // FALL THROUGH.
435 break;
436 default:
437 if (DS.getStorageClassSpecLoc().isValid())
438 Diag(DS.getStorageClassSpecLoc(),
439 diag::err_storageclass_invalid_for_member);
440 else
441 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
442 D.getMutableDeclSpec().ClearStorageClassSpecs();
443 }
444
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000445 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000446 if (!isFunc &&
447 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
448 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000449 // Check also for this case:
450 //
451 // typedef int f();
452 // f a;
453 //
454 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
455 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
456 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000457
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000459 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000460
461 Decl *Member;
462 bool InvalidDecl = false;
463
464 if (isInstField)
465 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
466 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000467 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000468
469 if (!Member) return LastInGroup;
470
Sanjiv Guptafa451432008-10-31 09:52:39 +0000471 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000472
473 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
474 // specific methods. Use a wrapper class that can be used with all C++ class
475 // member decls.
476 CXXClassMemberWrapper(Member).setAccess(AS);
477
Douglas Gregor15e04622008-11-05 16:20:31 +0000478 // C++ [dcl.init.aggr]p1:
479 // An aggregate is an array or a class (clause 9) with [...] no
480 // private or protected non-static data members (clause 11).
481 if (isInstField && (AS == AS_private || AS == AS_protected))
482 cast<CXXRecordDecl>(CurContext)->setAggregate(false);
483
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000484 if (DS.isVirtualSpecified()) {
485 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
486 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
487 InvalidDecl = true;
488 } else {
489 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
490 CurClass->setAggregate(false);
491 CurClass->setPolymorphic(true);
492 }
493 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000494
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000495 if (BitWidth) {
496 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
497 // constant-expression be a value equal to zero.
498 // FIXME: Check this.
499
500 if (D.isFunctionDeclarator()) {
501 // FIXME: Emit diagnostic about only constructors taking base initializers
502 // or something similar, when constructor support is in place.
503 Diag(Loc, diag::err_not_bitfield_type,
504 II->getName(), BitWidth->getSourceRange());
505 InvalidDecl = true;
506
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000507 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000508 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000509 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000510 Diag(Loc, diag::err_not_integral_type_bitfield,
511 II->getName(), BitWidth->getSourceRange());
512 InvalidDecl = true;
513 }
514
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000515 } else if (isa<FunctionDecl>(Member)) {
516 // A function typedef ("typedef int f(); f a;").
517 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
518 Diag(Loc, diag::err_not_integral_type_bitfield,
519 II->getName(), BitWidth->getSourceRange());
520 InvalidDecl = true;
521
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000522 } else if (isa<TypedefDecl>(Member)) {
523 // "cannot declare 'A' to be a bit-field type"
524 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
525 BitWidth->getSourceRange());
526 InvalidDecl = true;
527
528 } else {
529 assert(isa<CXXClassVarDecl>(Member) &&
530 "Didn't we cover all member kinds?");
531 // C++ 9.6p3: A bit-field shall not be a static member.
532 // "static member 'A' cannot be a bit-field"
533 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
534 BitWidth->getSourceRange());
535 InvalidDecl = true;
536 }
537 }
538
539 if (Init) {
540 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
541 // if it declares a static member of const integral or const enumeration
542 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000543 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
544 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000545 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000546 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000547 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
548 CVD->getType()->isIntegralType()) {
549 // constant-initializer
550 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000551 InvalidDecl = true;
552
553 } else {
554 // not const integral.
555 Diag(Loc, diag::err_member_initialization,
556 II->getName(), Init->getSourceRange());
557 InvalidDecl = true;
558 }
559
560 } else {
561 // not static member.
562 Diag(Loc, diag::err_member_initialization,
563 II->getName(), Init->getSourceRange());
564 InvalidDecl = true;
565 }
566 }
567
568 if (InvalidDecl)
569 Member->setInvalidDecl();
570
571 if (isInstField) {
572 FieldCollector->Add(cast<CXXFieldDecl>(Member));
573 return LastInGroup;
574 }
575 return Member;
576}
577
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000578/// ActOnMemInitializer - Handle a C++ member initializer.
579Sema::MemInitResult
580Sema::ActOnMemInitializer(DeclTy *ConstructorD,
581 Scope *S,
582 IdentifierInfo *MemberOrBase,
583 SourceLocation IdLoc,
584 SourceLocation LParenLoc,
585 ExprTy **Args, unsigned NumArgs,
586 SourceLocation *CommaLocs,
587 SourceLocation RParenLoc) {
588 CXXConstructorDecl *Constructor
589 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
590 if (!Constructor) {
591 // The user wrote a constructor initializer on a function that is
592 // not a C++ constructor. Ignore the error for now, because we may
593 // have more member initializers coming; we'll diagnose it just
594 // once in ActOnMemInitializers.
595 return true;
596 }
597
598 CXXRecordDecl *ClassDecl = Constructor->getParent();
599
600 // C++ [class.base.init]p2:
601 // Names in a mem-initializer-id are looked up in the scope of the
602 // constructor’s class and, if not found in that scope, are looked
603 // up in the scope containing the constructor’s
604 // definition. [Note: if the constructor’s class contains a member
605 // with the same name as a direct or virtual base class of the
606 // class, a mem-initializer-id naming the member or base class and
607 // composed of a single identifier refers to the class member. A
608 // mem-initializer-id for the hidden base class may be specified
609 // using a qualified name. ]
610 // Look for a member, first.
611 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase);
612
613 // FIXME: Handle members of an anonymous union.
614
615 if (Member) {
616 // FIXME: Perform direct initialization of the member.
617 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
618 }
619
620 // It didn't name a member, so see if it names a class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000621 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000622 if (!BaseTy)
623 return Diag(IdLoc, diag::err_mem_init_not_member_or_class,
624 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
625
626 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy);
627 if (!BaseType->isRecordType())
628 return Diag(IdLoc, diag::err_base_init_does_not_name_class,
629 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc));
630
631 // C++ [class.base.init]p2:
632 // [...] Unless the mem-initializer-id names a nonstatic data
633 // member of the constructor’s class or a direct or virtual base
634 // of that class, the mem-initializer is ill-formed. A
635 // mem-initializer-list can initialize a base class using any
636 // name that denotes that base class type.
637
638 // First, check for a direct base class.
639 const CXXBaseSpecifier *DirectBaseSpec = 0;
640 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
641 Base != ClassDecl->bases_end(); ++Base) {
642 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
643 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
644 // We found a direct base of this type. That's what we're
645 // initializing.
646 DirectBaseSpec = &*Base;
647 break;
648 }
649 }
650
651 // Check for a virtual base class.
652 // FIXME: We might be able to short-circuit this if we know in
653 // advance that there are no virtual bases.
654 const CXXBaseSpecifier *VirtualBaseSpec = 0;
655 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
656 // We haven't found a base yet; search the class hierarchy for a
657 // virtual base class.
658 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
659 /*DetectVirtual=*/false);
660 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
661 for (BasePaths::paths_iterator Path = Paths.begin();
662 Path != Paths.end(); ++Path) {
663 if (Path->back().Base->isVirtual()) {
664 VirtualBaseSpec = Path->back().Base;
665 break;
666 }
667 }
668 }
669 }
670
671 // C++ [base.class.init]p2:
672 // If a mem-initializer-id is ambiguous because it designates both
673 // a direct non-virtual base class and an inherited virtual base
674 // class, the mem-initializer is ill-formed.
675 if (DirectBaseSpec && VirtualBaseSpec)
676 return Diag(IdLoc, diag::err_base_init_direct_and_virtual,
677 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc));
678
679 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
680}
681
682
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000683void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
684 DeclTy *TagDecl,
685 SourceLocation LBrac,
686 SourceLocation RBrac) {
687 ActOnFields(S, RLoc, TagDecl,
688 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000689 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000690}
691
Douglas Gregore640ab62008-11-03 17:51:48 +0000692/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
693/// special functions, such as the default constructor, copy
694/// constructor, or destructor, to the given C++ class (C++
695/// [special]p1). This routine can only be executed just before the
696/// definition of the class is complete.
697void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
698 if (!ClassDecl->hasUserDeclaredConstructor()) {
699 // C++ [class.ctor]p5:
700 // A default constructor for a class X is a constructor of class X
701 // that can be called without an argument. If there is no
702 // user-declared constructor for class X, a default constructor is
703 // implicitly declared. An implicitly-declared default constructor
704 // is an inline public member of its class.
705 CXXConstructorDecl *DefaultCon =
706 CXXConstructorDecl::Create(Context, ClassDecl,
707 ClassDecl->getLocation(),
Douglas Gregorcbcb4c22008-11-12 23:21:09 +0000708 &Context.Idents.getConstructorId(),
Douglas Gregore640ab62008-11-03 17:51:48 +0000709 Context.getFunctionType(Context.VoidTy,
710 0, 0, false, 0),
711 /*isExplicit=*/false,
712 /*isInline=*/true,
713 /*isImplicitlyDeclared=*/true);
714 DefaultCon->setAccess(AS_public);
715 ClassDecl->addConstructor(Context, DefaultCon);
716 }
717
718 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
719 // C++ [class.copy]p4:
720 // If the class definition does not explicitly declare a copy
721 // constructor, one is declared implicitly.
722
723 // C++ [class.copy]p5:
724 // The implicitly-declared copy constructor for a class X will
725 // have the form
726 //
727 // X::X(const X&)
728 //
729 // if
730 bool HasConstCopyConstructor = true;
731
732 // -- each direct or virtual base class B of X has a copy
733 // constructor whose first parameter is of type const B& or
734 // const volatile B&, and
735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
736 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
737 const CXXRecordDecl *BaseClassDecl
738 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
739 HasConstCopyConstructor
740 = BaseClassDecl->hasConstCopyConstructor(Context);
741 }
742
743 // -- for all the nonstatic data members of X that are of a
744 // class type M (or array thereof), each such class type
745 // has a copy constructor whose first parameter is of type
746 // const M& or const volatile M&.
747 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
748 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
749 QualType FieldType = (*Field)->getType();
750 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
751 FieldType = Array->getElementType();
752 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
753 const CXXRecordDecl *FieldClassDecl
754 = cast<CXXRecordDecl>(FieldClassType->getDecl());
755 HasConstCopyConstructor
756 = FieldClassDecl->hasConstCopyConstructor(Context);
757 }
758 }
759
760 // Otherwise, the implicitly declared copy constructor will have
761 // the form
762 //
763 // X::X(X&)
764 QualType ArgType = Context.getTypeDeclType(ClassDecl);
765 if (HasConstCopyConstructor)
766 ArgType = ArgType.withConst();
767 ArgType = Context.getReferenceType(ArgType);
768
769 // An implicitly-declared copy constructor is an inline public
770 // member of its class.
771 CXXConstructorDecl *CopyConstructor
772 = CXXConstructorDecl::Create(Context, ClassDecl,
773 ClassDecl->getLocation(),
Douglas Gregorcbcb4c22008-11-12 23:21:09 +0000774 &Context.Idents.getConstructorId(),
Douglas Gregore640ab62008-11-03 17:51:48 +0000775 Context.getFunctionType(Context.VoidTy,
776 &ArgType, 1,
777 false, 0),
778 /*isExplicit=*/false,
779 /*isInline=*/true,
780 /*isImplicitlyDeclared=*/true);
781 CopyConstructor->setAccess(AS_public);
782
783 // Add the parameter to the constructor.
784 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
785 ClassDecl->getLocation(),
786 /*IdentifierInfo=*/0,
787 ArgType, VarDecl::None, 0, 0);
788 CopyConstructor->setParams(&FromParam, 1);
789
790 ClassDecl->addConstructor(Context, CopyConstructor);
791 }
792
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000793 if (!ClassDecl->getDestructor()) {
794 // C++ [class.dtor]p2:
795 // If a class has no user-declared destructor, a destructor is
796 // declared implicitly. An implicitly-declared destructor is an
797 // inline public member of its class.
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000798 CXXDestructorDecl *Destructor
799 = CXXDestructorDecl::Create(Context, ClassDecl,
800 ClassDecl->getLocation(),
Douglas Gregorcbcb4c22008-11-12 23:21:09 +0000801 &Context.Idents.getConstructorId(),
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000802 Context.getFunctionType(Context.VoidTy,
803 0, 0, false, 0),
804 /*isInline=*/true,
805 /*isImplicitlyDeclared=*/true);
806 Destructor->setAccess(AS_public);
807 ClassDecl->setDestructor(Destructor);
808 }
809
Douglas Gregore640ab62008-11-03 17:51:48 +0000810 // FIXME: Implicit copy assignment operator
811}
812
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000813void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000814 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000815 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000816 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000817 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000818
819 // Everything, including inline method definitions, have been parsed.
820 // Let the consumer know of the new TagDecl definition.
821 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000822}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000823
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000824/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
825/// the well-formednes of the constructor declarator @p D with type @p
826/// R. If there are any errors in the declarator, this routine will
827/// emit diagnostics and return true. Otherwise, it will return
828/// false. Either way, the type @p R will be updated to reflect a
829/// well-formed type for the constructor.
830bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
831 FunctionDecl::StorageClass& SC) {
832 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
833 bool isInvalid = false;
834
835 // C++ [class.ctor]p3:
836 // A constructor shall not be virtual (10.3) or static (9.4). A
837 // constructor can be invoked for a const, volatile or const
838 // volatile object. A constructor shall not be declared const,
839 // volatile, or const volatile (9.3.2).
840 if (isVirtual) {
841 Diag(D.getIdentifierLoc(),
842 diag::err_constructor_cannot_be,
843 "virtual",
844 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
845 SourceRange(D.getIdentifierLoc()));
846 isInvalid = true;
847 }
848 if (SC == FunctionDecl::Static) {
849 Diag(D.getIdentifierLoc(),
850 diag::err_constructor_cannot_be,
851 "static",
852 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
853 SourceRange(D.getIdentifierLoc()));
854 isInvalid = true;
855 SC = FunctionDecl::None;
856 }
857 if (D.getDeclSpec().hasTypeSpecifier()) {
858 // Constructors don't have return types, but the parser will
859 // happily parse something like:
860 //
861 // class X {
862 // float X(float);
863 // };
864 //
865 // The return type will be eliminated later.
866 Diag(D.getIdentifierLoc(),
867 diag::err_constructor_return_type,
868 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
869 SourceRange(D.getIdentifierLoc()));
870 }
871 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
872 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
873 if (FTI.TypeQuals & QualType::Const)
874 Diag(D.getIdentifierLoc(),
875 diag::err_invalid_qualified_constructor,
876 "const",
877 SourceRange(D.getIdentifierLoc()));
878 if (FTI.TypeQuals & QualType::Volatile)
879 Diag(D.getIdentifierLoc(),
880 diag::err_invalid_qualified_constructor,
881 "volatile",
882 SourceRange(D.getIdentifierLoc()));
883 if (FTI.TypeQuals & QualType::Restrict)
884 Diag(D.getIdentifierLoc(),
885 diag::err_invalid_qualified_constructor,
886 "restrict",
887 SourceRange(D.getIdentifierLoc()));
888 }
889
890 // Rebuild the function type "R" without any type qualifiers (in
891 // case any of the errors above fired) and with "void" as the
892 // return type, since constructors don't have return types. We
893 // *always* have to do this, because GetTypeForDeclarator will
894 // put in a result type of "int" when none was specified.
895 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
896 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
897 Proto->getNumArgs(),
898 Proto->isVariadic(),
899 0);
900
901 return isInvalid;
902}
903
904/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
905/// the well-formednes of the destructor declarator @p D with type @p
906/// R. If there are any errors in the declarator, this routine will
907/// emit diagnostics and return true. Otherwise, it will return
908/// false. Either way, the type @p R will be updated to reflect a
909/// well-formed type for the destructor.
910bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
911 FunctionDecl::StorageClass& SC) {
912 bool isInvalid = false;
913
914 // C++ [class.dtor]p1:
915 // [...] A typedef-name that names a class is a class-name
916 // (7.1.3); however, a typedef-name that names a class shall not
917 // be used as the identifier in the declarator for a destructor
918 // declaration.
919 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType();
920 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) {
Douglas Gregorbd19fdb2008-11-10 14:41:22 +0000921 Diag(D.getIdentifierLoc(),
922 diag::err_destructor_typedef_name,
923 TypedefD->getName());
924 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000925 }
926
927 // C++ [class.dtor]p2:
928 // A destructor is used to destroy objects of its class type. A
929 // destructor takes no parameters, and no return type can be
930 // specified for it (not even void). The address of a destructor
931 // shall not be taken. A destructor shall not be static. A
932 // destructor can be invoked for a const, volatile or const
933 // volatile object. A destructor shall not be declared const,
934 // volatile or const volatile (9.3.2).
935 if (SC == FunctionDecl::Static) {
936 Diag(D.getIdentifierLoc(),
937 diag::err_destructor_cannot_be,
938 "static",
939 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
940 SourceRange(D.getIdentifierLoc()));
941 isInvalid = true;
942 SC = FunctionDecl::None;
943 }
944 if (D.getDeclSpec().hasTypeSpecifier()) {
945 // Destructors don't have return types, but the parser will
946 // happily parse something like:
947 //
948 // class X {
949 // float ~X();
950 // };
951 //
952 // The return type will be eliminated later.
953 Diag(D.getIdentifierLoc(),
954 diag::err_destructor_return_type,
955 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
956 SourceRange(D.getIdentifierLoc()));
957 }
958 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
959 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
960 if (FTI.TypeQuals & QualType::Const)
961 Diag(D.getIdentifierLoc(),
962 diag::err_invalid_qualified_destructor,
963 "const",
964 SourceRange(D.getIdentifierLoc()));
965 if (FTI.TypeQuals & QualType::Volatile)
966 Diag(D.getIdentifierLoc(),
967 diag::err_invalid_qualified_destructor,
968 "volatile",
969 SourceRange(D.getIdentifierLoc()));
970 if (FTI.TypeQuals & QualType::Restrict)
971 Diag(D.getIdentifierLoc(),
972 diag::err_invalid_qualified_destructor,
973 "restrict",
974 SourceRange(D.getIdentifierLoc()));
975 }
976
977 // Make sure we don't have any parameters.
978 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
979 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
980
981 // Delete the parameters.
982 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
983 if (FTI.NumArgs) {
984 delete [] FTI.ArgInfo;
985 FTI.NumArgs = 0;
986 FTI.ArgInfo = 0;
987 }
988 }
989
990 // Make sure the destructor isn't variadic.
991 if (R->getAsFunctionTypeProto()->isVariadic())
992 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
993
994 // Rebuild the function type "R" without any type qualifiers or
995 // parameters (in case any of the errors above fired) and with
996 // "void" as the return type, since destructors don't have return
997 // types. We *always* have to do this, because GetTypeForDeclarator
998 // will put in a result type of "int" when none was specified.
999 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1000
1001 return isInvalid;
1002}
1003
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001004/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1005/// well-formednes of the conversion function declarator @p D with
1006/// type @p R. If there are any errors in the declarator, this routine
1007/// will emit diagnostics and return true. Otherwise, it will return
1008/// false. Either way, the type @p R will be updated to reflect a
1009/// well-formed type for the conversion operator.
1010bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1011 FunctionDecl::StorageClass& SC) {
1012 bool isInvalid = false;
1013
1014 // C++ [class.conv.fct]p1:
1015 // Neither parameter types nor return type can be specified. The
1016 // type of a conversion function (8.3.5) is “function taking no
1017 // parameter returning conversion-type-id.”
1018 if (SC == FunctionDecl::Static) {
1019 Diag(D.getIdentifierLoc(),
1020 diag::err_conv_function_not_member,
1021 "static",
1022 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
1023 SourceRange(D.getIdentifierLoc()));
1024 isInvalid = true;
1025 SC = FunctionDecl::None;
1026 }
1027 if (D.getDeclSpec().hasTypeSpecifier()) {
1028 // Conversion functions don't have return types, but the parser will
1029 // happily parse something like:
1030 //
1031 // class X {
1032 // float operator bool();
1033 // };
1034 //
1035 // The return type will be changed later anyway.
1036 Diag(D.getIdentifierLoc(),
1037 diag::err_conv_function_return_type,
1038 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
1039 SourceRange(D.getIdentifierLoc()));
1040 }
1041
1042 // Make sure we don't have any parameters.
1043 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) {
1044 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1045
1046 // Delete the parameters.
1047 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1048 if (FTI.NumArgs) {
1049 delete [] FTI.ArgInfo;
1050 FTI.NumArgs = 0;
1051 FTI.ArgInfo = 0;
1052 }
1053 }
1054
1055 // Make sure the conversion function isn't variadic.
1056 if (R->getAsFunctionTypeProto()->isVariadic())
1057 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1058
1059 // C++ [class.conv.fct]p4:
1060 // The conversion-type-id shall not represent a function type nor
1061 // an array type.
1062 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1063 if (ConvType->isArrayType()) {
1064 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1065 ConvType = Context.getPointerType(ConvType);
1066 } else if (ConvType->isFunctionType()) {
1067 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1068 ConvType = Context.getPointerType(ConvType);
1069 }
1070
1071 // Rebuild the function type "R" without any parameters (in case any
1072 // of the errors above fired) and with the conversion type as the
1073 // return type.
1074 R = Context.getFunctionType(ConvType, 0, 0, false,
1075 R->getAsFunctionTypeProto()->getTypeQuals());
1076
1077 return isInvalid;
1078}
1079
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001080/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
1081/// the declaration of the given C++ constructor ConDecl that was
1082/// built from declarator D. This routine is responsible for checking
1083/// that the newly-created constructor declaration is well-formed and
1084/// for recording it in the C++ class. Example:
1085///
1086/// @code
1087/// class X {
1088/// X(); // X::X() will be the ConDecl.
1089/// };
1090/// @endcode
1091Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
1092 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001093
1094 // Check default arguments on the constructor
1095 CheckCXXDefaultArguments(ConDecl);
1096
Douglas Gregorccabf082008-10-31 20:25:05 +00001097 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1098 if (!ClassDecl) {
1099 ConDecl->setInvalidDecl();
1100 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +00001101 }
1102
Douglas Gregorccabf082008-10-31 20:25:05 +00001103 // Make sure this constructor is an overload of the existing
1104 // constructors.
1105 OverloadedFunctionDecl::function_iterator MatchedDecl;
1106 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
1107 Diag(ConDecl->getLocation(),
1108 diag::err_constructor_redeclared,
1109 SourceRange(ConDecl->getLocation()));
1110 Diag((*MatchedDecl)->getLocation(),
1111 diag::err_previous_declaration,
1112 SourceRange((*MatchedDecl)->getLocation()));
1113 ConDecl->setInvalidDecl();
1114 return ConDecl;
1115 }
1116
1117
1118 // C++ [class.copy]p3:
1119 // A declaration of a constructor for a class X is ill-formed if
1120 // its first parameter is of type (optionally cv-qualified) X and
1121 // either there are no other parameters or else all other
1122 // parameters have default arguments.
1123 if ((ConDecl->getNumParams() == 1) ||
1124 (ConDecl->getNumParams() > 1 &&
1125 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
1126 QualType ParamType = ConDecl->getParamDecl(0)->getType();
1127 QualType ClassTy = Context.getTagDeclType(
1128 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
1129 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1130 Diag(ConDecl->getLocation(),
1131 diag::err_constructor_byvalue_arg,
1132 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
1133 ConDecl->setInvalidDecl();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001134 return ConDecl;
Douglas Gregorccabf082008-10-31 20:25:05 +00001135 }
1136 }
1137
1138 // Add this constructor to the set of constructors of the current
1139 // class.
1140 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001141 return (DeclTy *)ConDecl;
1142}
1143
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001144/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete
1145/// the declaration of the given C++ @p Destructor. This routine is
1146/// responsible for recording the destructor in the C++ class, if
1147/// possible.
1148Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) {
1149 assert(Destructor && "Expected to receive a destructor declaration");
1150
1151 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1152
1153 // Make sure we aren't redeclaring the destructor.
1154 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) {
1155 Diag(Destructor->getLocation(), diag::err_destructor_redeclared);
1156 Diag(PrevDestructor->getLocation(),
1157 PrevDestructor->isThisDeclarationADefinition()?
1158 diag::err_previous_definition
1159 : diag::err_previous_declaration);
1160 Destructor->setInvalidDecl();
1161 return Destructor;
1162 }
1163
1164 ClassDecl->setDestructor(Destructor);
1165 return (DeclTy *)Destructor;
1166}
1167
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001168/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1169/// the declaration of the given C++ conversion function. This routine
1170/// is responsible for recording the conversion function in the C++
1171/// class, if possible.
1172Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1173 assert(Conversion && "Expected to receive a conversion function declaration");
1174
1175 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext);
1176
1177 // Make sure we aren't redeclaring the conversion function.
1178 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1179 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1180 for (OverloadedFunctionDecl::function_iterator Func
1181 = Conversions->function_begin();
1182 Func != Conversions->function_end(); ++Func) {
1183 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func);
1184 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) {
1185 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared);
1186 Diag(OtherConv->getLocation(),
1187 OtherConv->isThisDeclarationADefinition()?
1188 diag::err_previous_definition
1189 : diag::err_previous_declaration);
1190 Conversion->setInvalidDecl();
1191 return (DeclTy *)Conversion;
1192 }
1193 }
1194
1195 // C++ [class.conv.fct]p1:
1196 // [...] A conversion function is never used to convert a
1197 // (possibly cv-qualified) object to the (possibly cv-qualified)
1198 // same object type (or a reference to it), to a (possibly
1199 // cv-qualified) base class of that type (or a reference to it),
1200 // or to (possibly cv-qualified) void.
1201 // FIXME: Suppress this warning if the conversion function ends up
1202 // being a virtual function that overrides a virtual function in a
1203 // base class.
1204 QualType ClassType
1205 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1206 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1207 ConvType = ConvTypeRef->getPointeeType();
1208 if (ConvType->isRecordType()) {
1209 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1210 if (ConvType == ClassType)
1211 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used,
1212 ClassType.getAsString());
1213 else if (IsDerivedFrom(ClassType, ConvType))
1214 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used,
1215 ClassType.getAsString(),
1216 ConvType.getAsString());
1217 } else if (ConvType->isVoidType()) {
1218 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used,
1219 ClassType.getAsString(), ConvType.getAsString());
1220 }
1221
1222 ClassDecl->addConversionFunction(Context, Conversion);
1223
1224 return (DeclTy *)Conversion;
1225}
1226
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001227//===----------------------------------------------------------------------===//
1228// Namespace Handling
1229//===----------------------------------------------------------------------===//
1230
1231/// ActOnStartNamespaceDef - This is called at the start of a namespace
1232/// definition.
1233Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1234 SourceLocation IdentLoc,
1235 IdentifierInfo *II,
1236 SourceLocation LBrace) {
1237 NamespaceDecl *Namespc =
1238 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1239 Namespc->setLBracLoc(LBrace);
1240
1241 Scope *DeclRegionScope = NamespcScope->getParent();
1242
1243 if (II) {
1244 // C++ [namespace.def]p2:
1245 // The identifier in an original-namespace-definition shall not have been
1246 // previously defined in the declarative region in which the
1247 // original-namespace-definition appears. The identifier in an
1248 // original-namespace-definition is the name of the namespace. Subsequently
1249 // in that declarative region, it is treated as an original-namespace-name.
1250
1251 Decl *PrevDecl =
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001252 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001253 /*enableLazyBuiltinCreation=*/false);
1254
Argiris Kirtzidisad9de132008-09-10 02:11:07 +00001255 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001256 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
1257 // This is an extended namespace definition.
1258 // Attach this namespace decl to the chain of extended namespace
1259 // definitions.
1260 NamespaceDecl *NextNS = OrigNS;
1261 while (NextNS->getNextNamespace())
1262 NextNS = NextNS->getNextNamespace();
1263
1264 NextNS->setNextNamespace(Namespc);
1265 Namespc->setOriginalNamespace(OrigNS);
1266
1267 // We won't add this decl to the current scope. We want the namespace
1268 // name to return the original namespace decl during a name lookup.
1269 } else {
1270 // This is an invalid name redefinition.
1271 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
1272 Namespc->getName());
1273 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1274 Namespc->setInvalidDecl();
1275 // Continue on to push Namespc as current DeclContext and return it.
1276 }
1277 } else {
1278 // This namespace name is declared for the first time.
1279 PushOnScopeChains(Namespc, DeclRegionScope);
1280 }
1281 }
1282 else {
1283 // FIXME: Handle anonymous namespaces
1284 }
1285
1286 // Although we could have an invalid decl (i.e. the namespace name is a
1287 // redefinition), push it as current DeclContext and try to continue parsing.
1288 PushDeclContext(Namespc->getOriginalNamespace());
1289 return Namespc;
1290}
1291
1292/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1293/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1294void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1295 Decl *Dcl = static_cast<Decl *>(D);
1296 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1297 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1298 Namespc->setRBracLoc(RBrace);
1299 PopDeclContext();
1300}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001301
1302
1303/// AddCXXDirectInitializerToDecl - This action is called immediately after
1304/// ActOnDeclarator, when a C++ direct initializer is present.
1305/// e.g: "int x(1);"
1306void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1307 ExprTy **ExprTys, unsigned NumExprs,
1308 SourceLocation *CommaLocs,
1309 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001310 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001311 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001312
1313 // If there is no declaration, there was an error parsing it. Just ignore
1314 // the initializer.
1315 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001316 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001317 delete static_cast<Expr *>(ExprTys[i]);
1318 return;
1319 }
1320
1321 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1322 if (!VDecl) {
1323 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1324 RealDecl->setInvalidDecl();
1325 return;
1326 }
1327
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001328 // We will treat direct-initialization as a copy-initialization:
1329 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001330 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1331 //
1332 // Clients that want to distinguish between the two forms, can check for
1333 // direct initializer using VarDecl::hasCXXDirectInitializer().
1334 // A major benefit is that clients that don't particularly care about which
1335 // exactly form was it (like the CodeGen) can handle both cases without
1336 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001337
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001338 // C++ 8.5p11:
1339 // The form of initialization (using parentheses or '=') is generally
1340 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001341 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001342 QualType DeclInitType = VDecl->getType();
1343 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1344 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001345
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001346 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001347 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001348 = PerformInitializationByConstructor(DeclInitType,
1349 (Expr **)ExprTys, NumExprs,
1350 VDecl->getLocation(),
1351 SourceRange(VDecl->getLocation(),
1352 RParenLoc),
1353 VDecl->getName(),
1354 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001355 if (!Constructor) {
1356 RealDecl->setInvalidDecl();
1357 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001358
1359 // Let clients know that initialization was done with a direct
1360 // initializer.
1361 VDecl->setCXXDirectInitializer(true);
1362
1363 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1364 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001365 return;
1366 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001367
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001368 if (NumExprs > 1) {
1369 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
1370 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001371 RealDecl->setInvalidDecl();
1372 return;
1373 }
1374
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001375 // Let clients know that initialization was done with a direct initializer.
1376 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001377
1378 assert(NumExprs == 1 && "Expected 1 expression");
1379 // Set the init expression, handles conversions.
1380 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001381}
Douglas Gregor81c29152008-10-29 00:13:59 +00001382
Douglas Gregor6428e762008-11-05 15:29:30 +00001383/// PerformInitializationByConstructor - Perform initialization by
1384/// constructor (C++ [dcl.init]p14), which may occur as part of
1385/// direct-initialization or copy-initialization. We are initializing
1386/// an object of type @p ClassType with the given arguments @p
1387/// Args. @p Loc is the location in the source code where the
1388/// initializer occurs (e.g., a declaration, member initializer,
1389/// functional cast, etc.) while @p Range covers the whole
1390/// initialization. @p InitEntity is the entity being initialized,
1391/// which may by the name of a declaration or a type. @p Kind is the
1392/// kind of initialization we're performing, which affects whether
1393/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001394/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001395/// when the initialization fails, emits a diagnostic and returns
1396/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001397CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001398Sema::PerformInitializationByConstructor(QualType ClassType,
1399 Expr **Args, unsigned NumArgs,
1400 SourceLocation Loc, SourceRange Range,
1401 std::string InitEntity,
1402 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001403 const RecordType *ClassRec = ClassType->getAsRecordType();
1404 assert(ClassRec && "Can only initialize a class type here");
1405
1406 // C++ [dcl.init]p14:
1407 //
1408 // If the initialization is direct-initialization, or if it is
1409 // copy-initialization where the cv-unqualified version of the
1410 // source type is the same class as, or a derived class of, the
1411 // class of the destination, constructors are considered. The
1412 // applicable constructors are enumerated (13.3.1.3), and the
1413 // best one is chosen through overload resolution (13.3). The
1414 // constructor so selected is called to initialize the object,
1415 // with the initializer expression(s) as its argument(s). If no
1416 // constructor applies, or the overload resolution is ambiguous,
1417 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001418 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1419 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001420
1421 // Add constructors to the overload set.
1422 OverloadedFunctionDecl *Constructors
1423 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors());
1424 for (OverloadedFunctionDecl::function_iterator Con
1425 = Constructors->function_begin();
1426 Con != Constructors->function_end(); ++Con) {
1427 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1428 if ((Kind == IK_Direct) ||
1429 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1430 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1431 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1432 }
1433
Douglas Gregor5870a952008-11-03 20:45:27 +00001434 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001435 switch (BestViableFunction(CandidateSet, Best)) {
1436 case OR_Success:
1437 // We found a constructor. Return it.
1438 return cast<CXXConstructorDecl>(Best->Function);
1439
1440 case OR_No_Viable_Function:
1441 if (CandidateSet.empty())
1442 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
1443 InitEntity, Range);
1444 else {
1445 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
1446 InitEntity, Range);
1447 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1448 }
1449 return 0;
1450
1451 case OR_Ambiguous:
1452 Diag(Loc, diag::err_ovl_ambiguous_init,
1453 InitEntity, Range);
1454 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1455 return 0;
1456 }
1457
1458 return 0;
1459}
1460
Douglas Gregor81c29152008-10-29 00:13:59 +00001461/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1462/// determine whether they are reference-related,
1463/// reference-compatible, reference-compatible with added
1464/// qualification, or incompatible, for use in C++ initialization by
1465/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1466/// type, and the first type (T1) is the pointee type of the reference
1467/// type being initialized.
1468Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001469Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1470 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001471 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1472 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1473
1474 T1 = Context.getCanonicalType(T1);
1475 T2 = Context.getCanonicalType(T2);
1476 QualType UnqualT1 = T1.getUnqualifiedType();
1477 QualType UnqualT2 = T2.getUnqualifiedType();
1478
1479 // C++ [dcl.init.ref]p4:
1480 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1481 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1482 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001483 if (UnqualT1 == UnqualT2)
1484 DerivedToBase = false;
1485 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1486 DerivedToBase = true;
1487 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001488 return Ref_Incompatible;
1489
1490 // At this point, we know that T1 and T2 are reference-related (at
1491 // least).
1492
1493 // C++ [dcl.init.ref]p4:
1494 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1495 // reference-related to T2 and cv1 is the same cv-qualification
1496 // as, or greater cv-qualification than, cv2. For purposes of
1497 // overload resolution, cases for which cv1 is greater
1498 // cv-qualification than cv2 are identified as
1499 // reference-compatible with added qualification (see 13.3.3.2).
1500 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1501 return Ref_Compatible;
1502 else if (T1.isMoreQualifiedThan(T2))
1503 return Ref_Compatible_With_Added_Qualification;
1504 else
1505 return Ref_Related;
1506}
1507
1508/// CheckReferenceInit - Check the initialization of a reference
1509/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1510/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001511/// list), and DeclType is the type of the declaration. When ICS is
1512/// non-null, this routine will compute the implicit conversion
1513/// sequence according to C++ [over.ics.ref] and will not produce any
1514/// diagnostics; when ICS is null, it will emit diagnostics when any
1515/// errors are found. Either way, a return value of true indicates
1516/// that there was a failure, a return value of false indicates that
1517/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001518///
1519/// When @p SuppressUserConversions, user-defined conversions are
1520/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001521bool
1522Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001523 ImplicitConversionSequence *ICS,
1524 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001525 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1526
1527 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1528 QualType T2 = Init->getType();
1529
Douglas Gregor45014fd2008-11-10 20:40:00 +00001530 // If the initializer is the address of an overloaded function, try
1531 // to resolve the overloaded function. If all goes well, T2 is the
1532 // type of the resulting function.
1533 if (T2->isOverloadType()) {
1534 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1535 ICS != 0);
1536 if (Fn) {
1537 // Since we're performing this reference-initialization for
1538 // real, update the initializer with the resulting function.
1539 if (!ICS)
1540 FixOverloadedFunctionReference(Init, Fn);
1541
1542 T2 = Fn->getType();
1543 }
1544 }
1545
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001546 // Compute some basic properties of the types and the initializer.
1547 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001548 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001549 ReferenceCompareResult RefRelationship
1550 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1551
1552 // Most paths end in a failed conversion.
1553 if (ICS)
1554 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001555
1556 // C++ [dcl.init.ref]p5:
1557 // A reference to type “cv1 T1” is initialized by an expression
1558 // of type “cv2 T2” as follows:
1559
1560 // -- If the initializer expression
1561
1562 bool BindsDirectly = false;
1563 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1564 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001565 //
1566 // Note that the bit-field check is skipped if we are just computing
1567 // the implicit conversion sequence (C++ [over.best.ics]p2).
1568 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1569 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001570 BindsDirectly = true;
1571
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001572 if (ICS) {
1573 // C++ [over.ics.ref]p1:
1574 // When a parameter of reference type binds directly (8.5.3)
1575 // to an argument expression, the implicit conversion sequence
1576 // is the identity conversion, unless the argument expression
1577 // has a type that is a derived class of the parameter type,
1578 // in which case the implicit conversion sequence is a
1579 // derived-to-base Conversion (13.3.3.1).
1580 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1581 ICS->Standard.First = ICK_Identity;
1582 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1583 ICS->Standard.Third = ICK_Identity;
1584 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1585 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001586 ICS->Standard.ReferenceBinding = true;
1587 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001588
1589 // Nothing more to do: the inaccessibility/ambiguity check for
1590 // derived-to-base conversions is suppressed when we're
1591 // computing the implicit conversion sequence (C++
1592 // [over.best.ics]p2).
1593 return false;
1594 } else {
1595 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001596 // FIXME: Binding to a subobject of the lvalue is going to require
1597 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001598 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001599 }
1600 }
1601
1602 // -- has a class type (i.e., T2 is a class type) and can be
1603 // implicitly converted to an lvalue of type “cv3 T3,”
1604 // where “cv1 T1” is reference-compatible with “cv3 T3”
1605 // 92) (this conversion is selected by enumerating the
1606 // applicable conversion functions (13.3.1.6) and choosing
1607 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001608 if (!SuppressUserConversions && T2->isRecordType()) {
1609 // FIXME: Look for conversions in base classes!
1610 CXXRecordDecl *T2RecordDecl
1611 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001612
Douglas Gregore6985fe2008-11-10 16:14:15 +00001613 OverloadCandidateSet CandidateSet;
1614 OverloadedFunctionDecl *Conversions
1615 = T2RecordDecl->getConversionFunctions();
1616 for (OverloadedFunctionDecl::function_iterator Func
1617 = Conversions->function_begin();
1618 Func != Conversions->function_end(); ++Func) {
1619 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1620
1621 // If the conversion function doesn't return a reference type,
1622 // it can't be considered for this conversion.
1623 // FIXME: This will change when we support rvalue references.
1624 if (Conv->getConversionType()->isReferenceType())
1625 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1626 }
1627
1628 OverloadCandidateSet::iterator Best;
1629 switch (BestViableFunction(CandidateSet, Best)) {
1630 case OR_Success:
1631 // This is a direct binding.
1632 BindsDirectly = true;
1633
1634 if (ICS) {
1635 // C++ [over.ics.ref]p1:
1636 //
1637 // [...] If the parameter binds directly to the result of
1638 // applying a conversion function to the argument
1639 // expression, the implicit conversion sequence is a
1640 // user-defined conversion sequence (13.3.3.1.2), with the
1641 // second standard conversion sequence either an identity
1642 // conversion or, if the conversion function returns an
1643 // entity of a type that is a derived class of the parameter
1644 // type, a derived-to-base Conversion.
1645 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1646 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1647 ICS->UserDefined.After = Best->FinalConversion;
1648 ICS->UserDefined.ConversionFunction = Best->Function;
1649 assert(ICS->UserDefined.After.ReferenceBinding &&
1650 ICS->UserDefined.After.DirectBinding &&
1651 "Expected a direct reference binding!");
1652 return false;
1653 } else {
1654 // Perform the conversion.
1655 // FIXME: Binding to a subobject of the lvalue is going to require
1656 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001657 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001658 }
1659 break;
1660
1661 case OR_Ambiguous:
1662 assert(false && "Ambiguous reference binding conversions not implemented.");
1663 return true;
1664
1665 case OR_No_Viable_Function:
1666 // There was no suitable conversion; continue with other checks.
1667 break;
1668 }
1669 }
1670
Douglas Gregor81c29152008-10-29 00:13:59 +00001671 if (BindsDirectly) {
1672 // C++ [dcl.init.ref]p4:
1673 // [...] In all cases where the reference-related or
1674 // reference-compatible relationship of two types is used to
1675 // establish the validity of a reference binding, and T1 is a
1676 // base class of T2, a program that necessitates such a binding
1677 // is ill-formed if T1 is an inaccessible (clause 11) or
1678 // ambiguous (10.2) base class of T2.
1679 //
1680 // Note that we only check this condition when we're allowed to
1681 // complain about errors, because we should not be checking for
1682 // ambiguity (or inaccessibility) unless the reference binding
1683 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001684 if (DerivedToBase)
1685 return CheckDerivedToBaseConversion(T2, T1,
1686 Init->getSourceRange().getBegin(),
1687 Init->getSourceRange());
1688 else
1689 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001690 }
1691
1692 // -- Otherwise, the reference shall be to a non-volatile const
1693 // type (i.e., cv1 shall be const).
1694 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001695 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001696 Diag(Init->getSourceRange().getBegin(),
1697 diag::err_not_reference_to_const_init,
1698 T1.getAsString(),
1699 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1700 T2.getAsString(), Init->getSourceRange());
1701 return true;
1702 }
1703
1704 // -- If the initializer expression is an rvalue, with T2 a
1705 // class type, and “cv1 T1” is reference-compatible with
1706 // “cv2 T2,” the reference is bound in one of the
1707 // following ways (the choice is implementation-defined):
1708 //
1709 // -- The reference is bound to the object represented by
1710 // the rvalue (see 3.10) or to a sub-object within that
1711 // object.
1712 //
1713 // -- A temporary of type “cv1 T2” [sic] is created, and
1714 // a constructor is called to copy the entire rvalue
1715 // object into the temporary. The reference is bound to
1716 // the temporary or to a sub-object within the
1717 // temporary.
1718 //
1719 //
1720 // The constructor that would be used to make the copy
1721 // shall be callable whether or not the copy is actually
1722 // done.
1723 //
1724 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1725 // freedom, so we will always take the first option and never build
1726 // a temporary in this case. FIXME: We will, however, have to check
1727 // for the presence of a copy constructor in C++98/03 mode.
1728 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001729 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1730 if (ICS) {
1731 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1732 ICS->Standard.First = ICK_Identity;
1733 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1734 ICS->Standard.Third = ICK_Identity;
1735 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1736 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001737 ICS->Standard.ReferenceBinding = true;
1738 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001739 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001740 // FIXME: Binding to a subobject of the rvalue is going to require
1741 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001742 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001743 }
1744 return false;
1745 }
1746
1747 // -- Otherwise, a temporary of type “cv1 T1” is created and
1748 // initialized from the initializer expression using the
1749 // rules for a non-reference copy initialization (8.5). The
1750 // reference is then bound to the temporary. If T1 is
1751 // reference-related to T2, cv1 must be the same
1752 // cv-qualification as, or greater cv-qualification than,
1753 // cv2; otherwise, the program is ill-formed.
1754 if (RefRelationship == Ref_Related) {
1755 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1756 // we would be reference-compatible or reference-compatible with
1757 // added qualification. But that wasn't the case, so the reference
1758 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001759 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001760 Diag(Init->getSourceRange().getBegin(),
1761 diag::err_reference_init_drops_quals,
1762 T1.getAsString(),
1763 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1764 T2.getAsString(), Init->getSourceRange());
1765 return true;
1766 }
1767
1768 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001769 if (ICS) {
1770 /// C++ [over.ics.ref]p2:
1771 ///
1772 /// When a parameter of reference type is not bound directly to
1773 /// an argument expression, the conversion sequence is the one
1774 /// required to convert the argument expression to the
1775 /// underlying type of the reference according to
1776 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1777 /// to copy-initializing a temporary of the underlying type with
1778 /// the argument expression. Any difference in top-level
1779 /// cv-qualification is subsumed by the initialization itself
1780 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001781 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001782 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1783 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001784 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001785 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001786}
Douglas Gregore60e5d32008-11-06 22:13:31 +00001787
1788/// CheckOverloadedOperatorDeclaration - Check whether the declaration
1789/// of this overloaded operator is well-formed. If so, returns false;
1790/// otherwise, emits appropriate diagnostics and returns true.
1791bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
1792 assert(FnDecl && FnDecl->getOverloadedOperator() != OO_None &&
1793 "Expected an overloaded operator declaration");
1794
1795 bool IsInvalid = false;
1796
1797 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
1798
1799 // C++ [over.oper]p5:
1800 // The allocation and deallocation functions, operator new,
1801 // operator new[], operator delete and operator delete[], are
1802 // described completely in 3.7.3. The attributes and restrictions
1803 // found in the rest of this subclause do not apply to them unless
1804 // explicitly stated in 3.7.3.
1805 // FIXME: Write a separate routine for checking this. For now, just
1806 // allow it.
1807 if (Op == OO_New || Op == OO_Array_New ||
1808 Op == OO_Delete || Op == OO_Array_Delete)
1809 return false;
1810
1811 // C++ [over.oper]p6:
1812 // An operator function shall either be a non-static member
1813 // function or be a non-member function and have at least one
1814 // parameter whose type is a class, a reference to a class, an
1815 // enumeration, or a reference to an enumeration.
1816 CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl);
1817 if (MethodDecl) {
1818 if (MethodDecl->isStatic()) {
1819 Diag(FnDecl->getLocation(),
1820 diag::err_operator_overload_static,
1821 FnDecl->getName(),
1822 SourceRange(FnDecl->getLocation()));
1823 IsInvalid = true;
1824
1825 // Pretend this isn't a member function; it'll supress
1826 // additional, unnecessary error messages.
1827 MethodDecl = 0;
1828 }
1829 } else {
1830 bool ClassOrEnumParam = false;
1831 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1832 Param != FnDecl->param_end(); ++Param) {
1833 QualType ParamType = (*Param)->getType();
1834 if (const ReferenceType *RefType = ParamType->getAsReferenceType())
1835 ParamType = RefType->getPointeeType();
1836 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
1837 ClassOrEnumParam = true;
1838 break;
1839 }
1840 }
1841
1842 if (!ClassOrEnumParam) {
1843 Diag(FnDecl->getLocation(),
1844 diag::err_operator_overload_needs_class_or_enum,
1845 FnDecl->getName(),
1846 SourceRange(FnDecl->getLocation()));
1847 IsInvalid = true;
1848 }
1849 }
1850
1851 // C++ [over.oper]p8:
1852 // An operator function cannot have default arguments (8.3.6),
1853 // except where explicitly stated below.
1854 //
1855 // Only the function-call operator allows default arguments
1856 // (C++ [over.call]p1).
1857 if (Op != OO_Call) {
1858 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
1859 Param != FnDecl->param_end(); ++Param) {
1860 if (Expr *DefArg = (*Param)->getDefaultArg()) {
1861 Diag((*Param)->getLocation(),
1862 diag::err_operator_overload_default_arg,
1863 DefArg->getSourceRange());
1864 IsInvalid = true;
1865 }
1866 }
1867 }
1868
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001869 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
1870 { false, false, false }
1871#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1872 , { Unary, Binary, MemberOnly }
1873#include "clang/Basic/OperatorKinds.def"
1874 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00001875
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001876 bool CanBeUnaryOperator = OperatorUses[Op][0];
1877 bool CanBeBinaryOperator = OperatorUses[Op][1];
1878 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00001879
1880 // C++ [over.oper]p8:
1881 // [...] Operator functions cannot have more or fewer parameters
1882 // than the number required for the corresponding operator, as
1883 // described in the rest of this subclause.
1884 unsigned NumParams = FnDecl->getNumParams() + (MethodDecl? 1 : 0);
1885 if (Op != OO_Call &&
1886 ((NumParams == 1 && !CanBeUnaryOperator) ||
1887 (NumParams == 2 && !CanBeBinaryOperator) ||
1888 (NumParams < 1) || (NumParams > 2))) {
1889 // We have the wrong number of parameters.
1890 std::string NumParamsStr = (llvm::APSInt(32) = NumParams).toString(10);
Douglas Gregore60e5d32008-11-06 22:13:31 +00001891
1892 diag::kind DK;
1893
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001894 if (CanBeUnaryOperator && CanBeBinaryOperator) {
1895 if (NumParams == 1)
1896 DK = diag::err_operator_overload_must_be_unary_or_binary;
1897 else
1898 DK = diag::err_operator_overload_must_be_unary_or_binary;
1899 } else if (CanBeUnaryOperator) {
1900 if (NumParams == 1)
1901 DK = diag::err_operator_overload_must_be_unary;
1902 else
1903 DK = diag::err_operator_overload_must_be_unary_plural;
1904 } else if (CanBeBinaryOperator) {
1905 if (NumParams == 1)
1906 DK = diag::err_operator_overload_must_be_binary;
1907 else
1908 DK = diag::err_operator_overload_must_be_binary_plural;
1909 } else {
Douglas Gregore60e5d32008-11-06 22:13:31 +00001910 assert(false && "All non-call overloaded operators are unary or binary!");
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001911 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00001912
1913 Diag(FnDecl->getLocation(), DK,
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001914 FnDecl->getName(), NumParamsStr,
Douglas Gregore60e5d32008-11-06 22:13:31 +00001915 SourceRange(FnDecl->getLocation()));
1916 IsInvalid = true;
1917 }
1918
1919 // Overloaded operators cannot be variadic.
1920 if (FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) {
1921 Diag(FnDecl->getLocation(),
1922 diag::err_operator_overload_variadic,
1923 SourceRange(FnDecl->getLocation()));
1924 IsInvalid = true;
1925 }
1926
1927 // Some operators must be non-static member functions.
1928 if (MustBeMemberOperator && !MethodDecl) {
1929 Diag(FnDecl->getLocation(),
1930 diag::err_operator_overload_must_be_member,
1931 FnDecl->getName(),
1932 SourceRange(FnDecl->getLocation()));
1933 IsInvalid = true;
1934 }
1935
1936 // C++ [over.inc]p1:
1937 // The user-defined function called operator++ implements the
1938 // prefix and postfix ++ operator. If this function is a member
1939 // function with no parameters, or a non-member function with one
1940 // parameter of class or enumeration type, it defines the prefix
1941 // increment operator ++ for objects of that type. If the function
1942 // is a member function with one parameter (which shall be of type
1943 // int) or a non-member function with two parameters (the second
1944 // of which shall be of type int), it defines the postfix
1945 // increment operator ++ for objects of that type.
1946 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
1947 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
1948 bool ParamIsInt = false;
1949 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
1950 ParamIsInt = BT->getKind() == BuiltinType::Int;
1951
1952 if (!ParamIsInt) {
Douglas Gregor9c6210b2008-11-10 13:38:07 +00001953 diag::kind DK;
1954 if (Op == OO_PlusPlus) {
1955 if (MethodDecl)
1956 DK = diag::err_operator_overload_post_inc_must_be_int_member;
1957 else
1958 DK = diag::err_operator_overload_post_inc_must_be_int;
1959 } else {
1960 if (MethodDecl)
1961 DK = diag::err_operator_overload_post_dec_must_be_int_member;
1962 else
1963 DK = diag::err_operator_overload_post_dec_must_be_int;
1964 }
1965 Diag(LastParam->getLocation(), DK,
Douglas Gregore60e5d32008-11-06 22:13:31 +00001966 Context.getCanonicalType(LastParam->getType()).getAsString(),
1967 SourceRange(FnDecl->getLocation()));
1968 IsInvalid = true;
1969 }
1970 }
1971
1972 return IsInvalid;
1973}