blob: f17875b986701750f4765a16ac2cb7ba853c6d1b [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"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000017#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000018#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000019#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000020#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner97316c02008-04-10 02:22:51 +000022#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000023#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000024#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000025
26using namespace clang;
27
Chris Lattner97316c02008-04-10 02:22:51 +000028//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
Chris Lattnerb1856db2008-04-12 23:52:44 +000032namespace {
33 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34 /// the default argument of a parameter to determine whether it
35 /// contains any ill-formed subexpressions. For example, this will
36 /// diagnose the use of local variables or parameters within the
37 /// default argument expression.
38 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000039 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000040 Expr *DefaultArg;
41 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000042
Chris Lattnerb1856db2008-04-12 23:52:44 +000043 public:
44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000046
Chris Lattnerb1856db2008-04-12 23:52:44 +000047 bool VisitExpr(Expr *Node);
48 bool VisitDeclRefExpr(DeclRefExpr *DRE);
49 };
Chris Lattner97316c02008-04-10 02:22:51 +000050
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 /// VisitExpr - Visit all of the children of this expression.
52 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
53 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000054 for (Stmt::child_iterator I = Node->child_begin(),
55 E = Node->child_end(); I != E; ++I)
56 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000057 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000058 }
59
Chris Lattnerb1856db2008-04-12 23:52:44 +000060 /// VisitDeclRefExpr - Visit a reference to a declaration, to
61 /// determine whether this declaration can be used in the default
62 /// argument expression.
63 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000064 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000065 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
66 // C++ [dcl.fct.default]p9
67 // Default arguments are evaluated each time the function is
68 // called. The order of evaluation of function arguments is
69 // unspecified. Consequently, parameters of a function shall not
70 // be used in default argument expressions, even if they are not
71 // evaluated. Parameters of a function declared before a default
72 // argument expression are in scope and can hide namespace and
73 // class member names.
74 return S->Diag(DRE->getSourceRange().getBegin(),
75 diag::err_param_default_argument_references_param,
76 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000078 // C++ [dcl.fct.default]p7
79 // Local variables shall not be used in default argument
80 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000081 if (VDecl->isBlockVarDecl())
82 return S->Diag(DRE->getSourceRange().getBegin(),
83 diag::err_param_default_argument_references_local,
84 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000085 }
Chris Lattner97316c02008-04-10 02:22:51 +000086
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 // FIXME: when Clang has support for member functions, "this"
88 // will also need to be diagnosed.
89
90 return false;
91 }
Chris Lattner97316c02008-04-10 02:22:51 +000092}
93
94/// ActOnParamDefaultArgument - Check whether the default argument
95/// provided for a function parameter is well-formed. If so, attach it
96/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +000097void
98Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
99 ExprTy *defarg) {
100 ParmVarDecl *Param = (ParmVarDecl *)param;
101 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
102 QualType ParamType = Param->getType();
103
104 // Default arguments are only permitted in C++
105 if (!getLangOptions().CPlusPlus) {
106 Diag(EqualLoc, diag::err_param_default_argument,
107 DefaultArg->getSourceRange());
108 return;
109 }
110
111 // C++ [dcl.fct.default]p5
112 // A default argument expression is implicitly converted (clause
113 // 4) to the parameter type. The default argument expression has
114 // the same semantic constraints as the initializer expression in
115 // a declaration of a variable of the parameter type, using the
116 // copy-initialization semantics (8.5).
117 //
118 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
119 // for C++ (since we want copy-initialization, not copy-assignment),
120 // but we don't have the right semantics implemented yet. Because of
121 // this, our error message is also very poor.
122 QualType DefaultArgType = DefaultArg->getType();
123 Expr *DefaultArgPtr = DefaultArg.get();
124 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
125 DefaultArgPtr);
126 if (DefaultArgPtr != DefaultArg.get()) {
127 DefaultArg.take();
128 DefaultArg.reset(DefaultArgPtr);
129 }
130 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
131 ParamType, DefaultArgType, DefaultArg.get(),
132 "in default argument")) {
133 return;
134 }
135
Chris Lattner97316c02008-04-10 02:22:51 +0000136 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000137 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000138 if (DefaultArgChecker.Visit(DefaultArg.get()))
139 return;
140
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(DefaultArg.take());
143}
144
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000145/// CheckExtraCXXDefaultArguments - Check for any extra default
146/// arguments in the declarator, which is not a function declaration
147/// or definition and therefore is not permitted to have default
148/// arguments. This routine should be invoked for every declarator
149/// that is not a function declaration or definition.
150void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
151 // C++ [dcl.fct.default]p3
152 // A default argument expression shall be specified only in the
153 // parameter-declaration-clause of a function declaration or in a
154 // template-parameter (14.1). It shall not be specified for a
155 // parameter pack. If it is specified in a
156 // parameter-declaration-clause, it shall not occur within a
157 // declarator or abstract-declarator of a parameter-declaration.
158 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
159 DeclaratorChunk &chunk = D.getTypeObject(i);
160 if (chunk.Kind == DeclaratorChunk::Function) {
161 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
162 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
163 if (Param->getDefaultArg()) {
164 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
165 Param->getDefaultArg()->getSourceRange());
166 Param->setDefaultArg(0);
167 }
168 }
169 }
170 }
171}
172
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000173// MergeCXXFunctionDecl - Merge two declarations of the same C++
174// function, once we already know that they have the same
175// type. Subroutine of MergeFunctionDecl.
176FunctionDecl *
177Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
178 // C++ [dcl.fct.default]p4:
179 //
180 // For non-template functions, default arguments can be added in
181 // later declarations of a function in the same
182 // scope. Declarations in different scopes have completely
183 // distinct sets of default arguments. That is, declarations in
184 // inner scopes do not acquire default arguments from
185 // declarations in outer scopes, and vice versa. In a given
186 // function declaration, all parameters subsequent to a
187 // parameter with a default argument shall have default
188 // arguments supplied in this or previous declarations. A
189 // default argument shall not be redefined by a later
190 // declaration (not even to the same value).
191 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
192 ParmVarDecl *OldParam = Old->getParamDecl(p);
193 ParmVarDecl *NewParam = New->getParamDecl(p);
194
195 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
196 Diag(NewParam->getLocation(),
197 diag::err_param_default_argument_redefinition,
198 NewParam->getDefaultArg()->getSourceRange());
199 Diag(OldParam->getLocation(), diag::err_previous_definition);
200 } else if (OldParam->getDefaultArg()) {
201 // Merge the old default argument into the new parameter
202 NewParam->setDefaultArg(OldParam->getDefaultArg());
203 }
204 }
205
206 return New;
207}
208
209/// CheckCXXDefaultArguments - Verify that the default arguments for a
210/// function declaration are well-formed according to C++
211/// [dcl.fct.default].
212void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
213 unsigned NumParams = FD->getNumParams();
214 unsigned p;
215
216 // Find first parameter with a default argument
217 for (p = 0; p < NumParams; ++p) {
218 ParmVarDecl *Param = FD->getParamDecl(p);
219 if (Param->getDefaultArg())
220 break;
221 }
222
223 // C++ [dcl.fct.default]p4:
224 // In a given function declaration, all parameters
225 // subsequent to a parameter with a default argument shall
226 // have default arguments supplied in this or previous
227 // declarations. A default argument shall not be redefined
228 // by a later declaration (not even to the same value).
229 unsigned LastMissingDefaultArg = 0;
230 for(; p < NumParams; ++p) {
231 ParmVarDecl *Param = FD->getParamDecl(p);
232 if (!Param->getDefaultArg()) {
233 if (Param->getIdentifier())
234 Diag(Param->getLocation(),
235 diag::err_param_default_argument_missing_name,
236 Param->getIdentifier()->getName());
237 else
238 Diag(Param->getLocation(),
239 diag::err_param_default_argument_missing);
240
241 LastMissingDefaultArg = p;
242 }
243 }
244
245 if (LastMissingDefaultArg > 0) {
246 // Some default arguments were missing. Clear out all of the
247 // default arguments up to (and including) the last missing
248 // default argument, so that we leave the function parameters
249 // in a semantically valid state.
250 for (p = 0; p <= LastMissingDefaultArg; ++p) {
251 ParmVarDecl *Param = FD->getParamDecl(p);
252 if (Param->getDefaultArg()) {
253 delete Param->getDefaultArg();
254 Param->setDefaultArg(0);
255 }
256 }
257 }
258}
Douglas Gregorec93f442008-04-13 21:30:24 +0000259
260/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
261/// one entry in the base class list of a class specifier, for
262/// example:
263/// class foo : public bar, virtual private baz {
264/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000265Sema::BaseResult
266Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
267 bool Virtual, AccessSpecifier Access,
268 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000269 RecordDecl *Decl = (RecordDecl*)classdecl;
270 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
271
272 // Base specifiers must be record types.
273 if (!BaseType->isRecordType()) {
274 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000275 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000276 }
277
278 // C++ [class.union]p1:
279 // A union shall not be used as a base class.
280 if (BaseType->isUnionType()) {
281 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000282 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000283 }
284
285 // C++ [class.union]p1:
286 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000287 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000288 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
289 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000290 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000291 }
292
293 // C++ [class.derived]p2:
294 // The class-name in a base-specifier shall not be an incompletely
295 // defined class.
296 if (BaseType->isIncompleteType()) {
297 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000298 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000299 }
300
Douglas Gregorabed2172008-10-22 17:49:05 +0000301 // Create the base specifier.
302 CXXBaseSpecifier *BS = CXXBaseSpecifier::Create(Context, SpecifierRange,
303 Virtual,
304 BaseType->isClassType(),
305 Access, BaseType);
306 return BS;
307}
Douglas Gregorec93f442008-04-13 21:30:24 +0000308
Douglas Gregorabed2172008-10-22 17:49:05 +0000309/// ActOnBaseSpecifiers - Attach the given base specifiers to the
310/// class, after checking whether there are any duplicate base
311/// classes.
312void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
313 unsigned NumBases) {
314 if (NumBases == 0)
315 return;
316
317 // Used to keep track of which base types we have already seen, so
318 // that we can properly diagnose redundant direct base types. Note
319 // that the key is always the canonical type.
320 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
321
322 // Copy non-redundant base specifiers into permanent storage.
323 CXXBaseSpecifier **InBaseSpecs = (CXXBaseSpecifier **)Bases;
324 CXXBaseSpecifier **StoredBaseSpecs = new CXXBaseSpecifier* [NumBases];
325 unsigned outIdx = 0;
326 for (unsigned inIdx = 0; inIdx < NumBases; ++inIdx) {
327 QualType NewBaseType
328 = Context.getCanonicalType(InBaseSpecs[inIdx]->getType());
329 if (KnownBaseTypes[NewBaseType]) {
330 // C++ [class.mi]p3:
331 // A class shall not be specified as a direct base class of a
332 // derived class more than once.
333 Diag(InBaseSpecs[inIdx]->getSourceRange().getBegin(),
334 diag::err_duplicate_base_class,
335 KnownBaseTypes[NewBaseType]->getType().getAsString(),
336 InBaseSpecs[inIdx]->getSourceRange());
337 } else {
338 // Okay, add this new base class.
339 KnownBaseTypes[NewBaseType] = InBaseSpecs[inIdx];
340 StoredBaseSpecs[outIdx++] = InBaseSpecs[inIdx];
341 }
342 }
343
344 // Attach the remaining base class specifiers to the derived class.
345 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
346 Decl->setBases(StoredBaseSpecs, outIdx);
Douglas Gregorec93f442008-04-13 21:30:24 +0000347}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000348
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000349//===----------------------------------------------------------------------===//
350// C++ class member Handling
351//===----------------------------------------------------------------------===//
352
353/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
354/// definition, when on C++.
355void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
356 Decl *Dcl = static_cast<Decl *>(D);
357 PushDeclContext(cast<CXXRecordDecl>(Dcl));
358 FieldCollector->StartClass();
359}
360
361/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
362/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
363/// bitfield width if there is one and 'InitExpr' specifies the initializer if
364/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
365/// declarators on it.
366///
367/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
368/// an instance field is declared, a new CXXFieldDecl is created but the method
369/// does *not* return it; it returns LastInGroup instead. The other C++ members
370/// (which are all ScopedDecls) are returned after appending them to
371/// LastInGroup.
372Sema::DeclTy *
373Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
374 ExprTy *BW, ExprTy *InitExpr,
375 DeclTy *LastInGroup) {
376 const DeclSpec &DS = D.getDeclSpec();
377 IdentifierInfo *II = D.getIdentifier();
378 Expr *BitWidth = static_cast<Expr*>(BW);
379 Expr *Init = static_cast<Expr*>(InitExpr);
380 SourceLocation Loc = D.getIdentifierLoc();
381
382 // C++ 9.2p6: A member shall not be declared to have automatic storage
383 // duration (auto, register) or with the extern storage-class-specifier.
384 switch (DS.getStorageClassSpec()) {
385 case DeclSpec::SCS_unspecified:
386 case DeclSpec::SCS_typedef:
387 case DeclSpec::SCS_static:
388 // FALL THROUGH.
389 break;
390 default:
391 if (DS.getStorageClassSpecLoc().isValid())
392 Diag(DS.getStorageClassSpecLoc(),
393 diag::err_storageclass_invalid_for_member);
394 else
395 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
396 D.getMutableDeclSpec().ClearStorageClassSpecs();
397 }
398
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000399 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000400 if (!isFunc &&
401 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
402 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000403 // Check also for this case:
404 //
405 // typedef int f();
406 // f a;
407 //
408 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
409 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
410 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000411
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000412 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000413 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000414
415 Decl *Member;
416 bool InvalidDecl = false;
417
418 if (isInstField)
419 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
420 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000421 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000422
423 if (!Member) return LastInGroup;
424
425 assert(II || isInstField && "No identifier for non-field ?");
426
427 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
428 // specific methods. Use a wrapper class that can be used with all C++ class
429 // member decls.
430 CXXClassMemberWrapper(Member).setAccess(AS);
431
432 if (BitWidth) {
433 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
434 // constant-expression be a value equal to zero.
435 // FIXME: Check this.
436
437 if (D.isFunctionDeclarator()) {
438 // FIXME: Emit diagnostic about only constructors taking base initializers
439 // or something similar, when constructor support is in place.
440 Diag(Loc, diag::err_not_bitfield_type,
441 II->getName(), BitWidth->getSourceRange());
442 InvalidDecl = true;
443
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000444 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000445 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000446 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000447 Diag(Loc, diag::err_not_integral_type_bitfield,
448 II->getName(), BitWidth->getSourceRange());
449 InvalidDecl = true;
450 }
451
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000452 } else if (isa<FunctionDecl>(Member)) {
453 // A function typedef ("typedef int f(); f a;").
454 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
455 Diag(Loc, diag::err_not_integral_type_bitfield,
456 II->getName(), BitWidth->getSourceRange());
457 InvalidDecl = true;
458
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000459 } else if (isa<TypedefDecl>(Member)) {
460 // "cannot declare 'A' to be a bit-field type"
461 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
462 BitWidth->getSourceRange());
463 InvalidDecl = true;
464
465 } else {
466 assert(isa<CXXClassVarDecl>(Member) &&
467 "Didn't we cover all member kinds?");
468 // C++ 9.6p3: A bit-field shall not be a static member.
469 // "static member 'A' cannot be a bit-field"
470 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
471 BitWidth->getSourceRange());
472 InvalidDecl = true;
473 }
474 }
475
476 if (Init) {
477 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
478 // if it declares a static member of const integral or const enumeration
479 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000480 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
481 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000482 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000483 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000484 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
485 CVD->getType()->isIntegralType()) {
486 // constant-initializer
487 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000488 InvalidDecl = true;
489
490 } else {
491 // not const integral.
492 Diag(Loc, diag::err_member_initialization,
493 II->getName(), Init->getSourceRange());
494 InvalidDecl = true;
495 }
496
497 } else {
498 // not static member.
499 Diag(Loc, diag::err_member_initialization,
500 II->getName(), Init->getSourceRange());
501 InvalidDecl = true;
502 }
503 }
504
505 if (InvalidDecl)
506 Member->setInvalidDecl();
507
508 if (isInstField) {
509 FieldCollector->Add(cast<CXXFieldDecl>(Member));
510 return LastInGroup;
511 }
512 return Member;
513}
514
515void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
516 DeclTy *TagDecl,
517 SourceLocation LBrac,
518 SourceLocation RBrac) {
519 ActOnFields(S, RLoc, TagDecl,
520 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000521 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000522}
523
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000524void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000525 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000526 FieldCollector->FinishClass();
527 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000528
529 // Everything, including inline method definitions, have been parsed.
530 // Let the consumer know of the new TagDecl definition.
531 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000532}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000533
534//===----------------------------------------------------------------------===//
535// Namespace Handling
536//===----------------------------------------------------------------------===//
537
538/// ActOnStartNamespaceDef - This is called at the start of a namespace
539/// definition.
540Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
541 SourceLocation IdentLoc,
542 IdentifierInfo *II,
543 SourceLocation LBrace) {
544 NamespaceDecl *Namespc =
545 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
546 Namespc->setLBracLoc(LBrace);
547
548 Scope *DeclRegionScope = NamespcScope->getParent();
549
550 if (II) {
551 // C++ [namespace.def]p2:
552 // The identifier in an original-namespace-definition shall not have been
553 // previously defined in the declarative region in which the
554 // original-namespace-definition appears. The identifier in an
555 // original-namespace-definition is the name of the namespace. Subsequently
556 // in that declarative region, it is treated as an original-namespace-name.
557
558 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +0000559 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000560 /*enableLazyBuiltinCreation=*/false);
561
Argiris Kirtzidisad9de132008-09-10 02:11:07 +0000562 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000563 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
564 // This is an extended namespace definition.
565 // Attach this namespace decl to the chain of extended namespace
566 // definitions.
567 NamespaceDecl *NextNS = OrigNS;
568 while (NextNS->getNextNamespace())
569 NextNS = NextNS->getNextNamespace();
570
571 NextNS->setNextNamespace(Namespc);
572 Namespc->setOriginalNamespace(OrigNS);
573
574 // We won't add this decl to the current scope. We want the namespace
575 // name to return the original namespace decl during a name lookup.
576 } else {
577 // This is an invalid name redefinition.
578 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
579 Namespc->getName());
580 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
581 Namespc->setInvalidDecl();
582 // Continue on to push Namespc as current DeclContext and return it.
583 }
584 } else {
585 // This namespace name is declared for the first time.
586 PushOnScopeChains(Namespc, DeclRegionScope);
587 }
588 }
589 else {
590 // FIXME: Handle anonymous namespaces
591 }
592
593 // Although we could have an invalid decl (i.e. the namespace name is a
594 // redefinition), push it as current DeclContext and try to continue parsing.
595 PushDeclContext(Namespc->getOriginalNamespace());
596 return Namespc;
597}
598
599/// ActOnFinishNamespaceDef - This callback is called after a namespace is
600/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
601void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
602 Decl *Dcl = static_cast<Decl *>(D);
603 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
604 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
605 Namespc->setRBracLoc(RBrace);
606 PopDeclContext();
607}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000608
609
610/// AddCXXDirectInitializerToDecl - This action is called immediately after
611/// ActOnDeclarator, when a C++ direct initializer is present.
612/// e.g: "int x(1);"
613void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
614 ExprTy **ExprTys, unsigned NumExprs,
615 SourceLocation *CommaLocs,
616 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000617 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000618 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000619
620 // If there is no declaration, there was an error parsing it. Just ignore
621 // the initializer.
622 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +0000623 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000624 delete static_cast<Expr *>(ExprTys[i]);
625 return;
626 }
627
628 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
629 if (!VDecl) {
630 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
631 RealDecl->setInvalidDecl();
632 return;
633 }
634
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000635 // We will treat direct-initialization as a copy-initialization:
636 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000637 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
638 //
639 // Clients that want to distinguish between the two forms, can check for
640 // direct initializer using VarDecl::hasCXXDirectInitializer().
641 // A major benefit is that clients that don't particularly care about which
642 // exactly form was it (like the CodeGen) can handle both cases without
643 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000644
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000645 // C++ 8.5p11:
646 // The form of initialization (using parentheses or '=') is generally
647 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000648 // class type.
649
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000650 if (VDecl->getType()->isRecordType()) {
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000651 // FIXME: When constructors for class types are supported, determine how
652 // exactly semantic checking will be done for direct initializers.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000653 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
654 "initialization for class types is not handled yet");
655 Diag(VDecl->getLocation(), DiagID);
656 RealDecl->setInvalidDecl();
657 return;
658 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000659
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000660 if (NumExprs > 1) {
661 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
662 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000663 RealDecl->setInvalidDecl();
664 return;
665 }
666
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000667 // Let clients know that initialization was done with a direct initializer.
668 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000669
670 assert(NumExprs == 1 && "Expected 1 expression");
671 // Set the init expression, handles conversions.
672 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000673}