blob: 7c4444fab61113b525217fbfadbcd45b28d24e0b [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Chris Lattner8123a952008-04-10 02:22:51 +000017#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000018#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner8123a952008-04-10 02:22:51 +000021#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000022#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000023#include <functional>
24#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000025
26using namespace clang;
27
Chris Lattner8123a952008-04-10 02:22:51 +000028//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
Chris Lattner9e979552008-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 Lattnerb77792e2008-07-26 22:17:49 +000039 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000040 Expr *DefaultArg;
41 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000042
Chris Lattner9e979552008-04-12 23:52:44 +000043 public:
44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 bool VisitExpr(Expr *Node);
48 bool VisitDeclRefExpr(DeclRefExpr *DRE);
49 };
Chris Lattner8123a952008-04-10 02:22:51 +000050
Chris Lattner9e979552008-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 Lattnerb77792e2008-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 Lattner9e979552008-04-12 23:52:44 +000057 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000058 }
59
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000064 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Naroff248a7532008-04-15 22:42:06 +000077 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000078 // C++ [dcl.fct.default]p7
79 // Local variables shall not be used in default argument
80 // expressions.
Steve Naroff248a7532008-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 Lattner9e979552008-04-12 23:52:44 +000085 }
Chris Lattner8123a952008-04-10 02:22:51 +000086
Chris Lattner9e979552008-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 Lattner8123a952008-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 Lattner3d1cee32008-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 Lattner8123a952008-04-10 02:22:51 +0000136 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000137 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner8123a952008-04-10 02:22:51 +0000138 if (DefaultArgChecker.Visit(DefaultArg.get()))
139 return;
140
Chris Lattner3d1cee32008-04-08 05:04:30 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(DefaultArg.take());
143}
144
Douglas Gregor6d6eb572008-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 Lattner3d1cee32008-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 Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000265Sema::BaseResult
266Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
267 bool Virtual, AccessSpecifier Access,
268 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000275 return true;
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000282 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000283 }
284
285 // C++ [class.union]p1:
286 // A union shall not have base classes.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000287 if (Decl->isUnion()) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000288 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
289 SpecifierRange);
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000290 return true;
Douglas Gregore37ac4f2008-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 Gregorf8268ae2008-10-22 17:49:05 +0000298 return true;
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000299 }
300
Douglas Gregorf8268ae2008-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 Gregore37ac4f2008-04-13 21:30:24 +0000308
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000309/// QualTypeOrder - Function object that provides a total ordering on
310/// QualType values.
311struct QualTypeOrdering : std::binary_function<QualType, QualType, bool> {
312 bool operator()(QualType T1, QualType T2) {
313 return std::less<void*>()(T1.getAsOpaquePtr(), T2.getAsOpaquePtr());
314 }
315};
316
317/// ActOnBaseSpecifiers - Attach the given base specifiers to the
318/// class, after checking whether there are any duplicate base
319/// classes.
320void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
321 unsigned NumBases) {
322 if (NumBases == 0)
323 return;
324
325 // Used to keep track of which base types we have already seen, so
326 // that we can properly diagnose redundant direct base types. Note
327 // that the key is always the canonical type.
328 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
329
330 // Copy non-redundant base specifiers into permanent storage.
331 CXXBaseSpecifier **InBaseSpecs = (CXXBaseSpecifier **)Bases;
332 CXXBaseSpecifier **StoredBaseSpecs = new CXXBaseSpecifier* [NumBases];
333 unsigned outIdx = 0;
334 for (unsigned inIdx = 0; inIdx < NumBases; ++inIdx) {
335 QualType NewBaseType
336 = Context.getCanonicalType(InBaseSpecs[inIdx]->getType());
337 if (KnownBaseTypes[NewBaseType]) {
338 // C++ [class.mi]p3:
339 // A class shall not be specified as a direct base class of a
340 // derived class more than once.
341 Diag(InBaseSpecs[inIdx]->getSourceRange().getBegin(),
342 diag::err_duplicate_base_class,
343 KnownBaseTypes[NewBaseType]->getType().getAsString(),
344 InBaseSpecs[inIdx]->getSourceRange());
345 } else {
346 // Okay, add this new base class.
347 KnownBaseTypes[NewBaseType] = InBaseSpecs[inIdx];
348 StoredBaseSpecs[outIdx++] = InBaseSpecs[inIdx];
349 }
350 }
351
352 // Attach the remaining base class specifiers to the derived class.
353 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
354 Decl->setBases(StoredBaseSpecs, outIdx);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000355}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000356
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000357//===----------------------------------------------------------------------===//
358// C++ class member Handling
359//===----------------------------------------------------------------------===//
360
361/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
362/// definition, when on C++.
363void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
364 Decl *Dcl = static_cast<Decl *>(D);
365 PushDeclContext(cast<CXXRecordDecl>(Dcl));
366 FieldCollector->StartClass();
367}
368
369/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
370/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
371/// bitfield width if there is one and 'InitExpr' specifies the initializer if
372/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
373/// declarators on it.
374///
375/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
376/// an instance field is declared, a new CXXFieldDecl is created but the method
377/// does *not* return it; it returns LastInGroup instead. The other C++ members
378/// (which are all ScopedDecls) are returned after appending them to
379/// LastInGroup.
380Sema::DeclTy *
381Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
382 ExprTy *BW, ExprTy *InitExpr,
383 DeclTy *LastInGroup) {
384 const DeclSpec &DS = D.getDeclSpec();
385 IdentifierInfo *II = D.getIdentifier();
386 Expr *BitWidth = static_cast<Expr*>(BW);
387 Expr *Init = static_cast<Expr*>(InitExpr);
388 SourceLocation Loc = D.getIdentifierLoc();
389
390 // C++ 9.2p6: A member shall not be declared to have automatic storage
391 // duration (auto, register) or with the extern storage-class-specifier.
392 switch (DS.getStorageClassSpec()) {
393 case DeclSpec::SCS_unspecified:
394 case DeclSpec::SCS_typedef:
395 case DeclSpec::SCS_static:
396 // FALL THROUGH.
397 break;
398 default:
399 if (DS.getStorageClassSpecLoc().isValid())
400 Diag(DS.getStorageClassSpecLoc(),
401 diag::err_storageclass_invalid_for_member);
402 else
403 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
404 D.getMutableDeclSpec().ClearStorageClassSpecs();
405 }
406
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000407 bool isFunc = D.isFunctionDeclarator();
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000408 if (!isFunc &&
409 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
410 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000411 // Check also for this case:
412 //
413 // typedef int f();
414 // f a;
415 //
416 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
417 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
418 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000419
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000420 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000421 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000422
423 Decl *Member;
424 bool InvalidDecl = false;
425
426 if (isInstField)
427 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
428 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000429 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000430
431 if (!Member) return LastInGroup;
432
433 assert(II || isInstField && "No identifier for non-field ?");
434
435 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
436 // specific methods. Use a wrapper class that can be used with all C++ class
437 // member decls.
438 CXXClassMemberWrapper(Member).setAccess(AS);
439
440 if (BitWidth) {
441 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
442 // constant-expression be a value equal to zero.
443 // FIXME: Check this.
444
445 if (D.isFunctionDeclarator()) {
446 // FIXME: Emit diagnostic about only constructors taking base initializers
447 // or something similar, when constructor support is in place.
448 Diag(Loc, diag::err_not_bitfield_type,
449 II->getName(), BitWidth->getSourceRange());
450 InvalidDecl = true;
451
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000452 } else if (isInstField) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000453 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000454 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000455 Diag(Loc, diag::err_not_integral_type_bitfield,
456 II->getName(), BitWidth->getSourceRange());
457 InvalidDecl = true;
458 }
459
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000460 } else if (isa<FunctionDecl>(Member)) {
461 // A function typedef ("typedef int f(); f a;").
462 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
463 Diag(Loc, diag::err_not_integral_type_bitfield,
464 II->getName(), BitWidth->getSourceRange());
465 InvalidDecl = true;
466
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000467 } else if (isa<TypedefDecl>(Member)) {
468 // "cannot declare 'A' to be a bit-field type"
469 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
470 BitWidth->getSourceRange());
471 InvalidDecl = true;
472
473 } else {
474 assert(isa<CXXClassVarDecl>(Member) &&
475 "Didn't we cover all member kinds?");
476 // C++ 9.6p3: A bit-field shall not be a static member.
477 // "static member 'A' cannot be a bit-field"
478 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
479 BitWidth->getSourceRange());
480 InvalidDecl = true;
481 }
482 }
483
484 if (Init) {
485 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
486 // if it declares a static member of const integral or const enumeration
487 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000488 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
489 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000490 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000491 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000492 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
493 CVD->getType()->isIntegralType()) {
494 // constant-initializer
495 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000496 InvalidDecl = true;
497
498 } else {
499 // not const integral.
500 Diag(Loc, diag::err_member_initialization,
501 II->getName(), Init->getSourceRange());
502 InvalidDecl = true;
503 }
504
505 } else {
506 // not static member.
507 Diag(Loc, diag::err_member_initialization,
508 II->getName(), Init->getSourceRange());
509 InvalidDecl = true;
510 }
511 }
512
513 if (InvalidDecl)
514 Member->setInvalidDecl();
515
516 if (isInstField) {
517 FieldCollector->Add(cast<CXXFieldDecl>(Member));
518 return LastInGroup;
519 }
520 return Member;
521}
522
523void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
524 DeclTy *TagDecl,
525 SourceLocation LBrac,
526 SourceLocation RBrac) {
527 ActOnFields(S, RLoc, TagDecl,
528 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000529 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000530}
531
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000532void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000533 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000534 FieldCollector->FinishClass();
535 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000536
537 // Everything, including inline method definitions, have been parsed.
538 // Let the consumer know of the new TagDecl definition.
539 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000540}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000541
542//===----------------------------------------------------------------------===//
543// Namespace Handling
544//===----------------------------------------------------------------------===//
545
546/// ActOnStartNamespaceDef - This is called at the start of a namespace
547/// definition.
548Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
549 SourceLocation IdentLoc,
550 IdentifierInfo *II,
551 SourceLocation LBrace) {
552 NamespaceDecl *Namespc =
553 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
554 Namespc->setLBracLoc(LBrace);
555
556 Scope *DeclRegionScope = NamespcScope->getParent();
557
558 if (II) {
559 // C++ [namespace.def]p2:
560 // The identifier in an original-namespace-definition shall not have been
561 // previously defined in the declarative region in which the
562 // original-namespace-definition appears. The identifier in an
563 // original-namespace-definition is the name of the namespace. Subsequently
564 // in that declarative region, it is treated as an original-namespace-name.
565
566 Decl *PrevDecl =
Argyrios Kyrtzidis154d8e22008-10-14 18:28:48 +0000567 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000568 /*enableLazyBuiltinCreation=*/false);
569
Argyrios Kyrtzidis2fac6262008-09-10 02:11:07 +0000570 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000571 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
572 // This is an extended namespace definition.
573 // Attach this namespace decl to the chain of extended namespace
574 // definitions.
575 NamespaceDecl *NextNS = OrigNS;
576 while (NextNS->getNextNamespace())
577 NextNS = NextNS->getNextNamespace();
578
579 NextNS->setNextNamespace(Namespc);
580 Namespc->setOriginalNamespace(OrigNS);
581
582 // We won't add this decl to the current scope. We want the namespace
583 // name to return the original namespace decl during a name lookup.
584 } else {
585 // This is an invalid name redefinition.
586 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
587 Namespc->getName());
588 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
589 Namespc->setInvalidDecl();
590 // Continue on to push Namespc as current DeclContext and return it.
591 }
592 } else {
593 // This namespace name is declared for the first time.
594 PushOnScopeChains(Namespc, DeclRegionScope);
595 }
596 }
597 else {
598 // FIXME: Handle anonymous namespaces
599 }
600
601 // Although we could have an invalid decl (i.e. the namespace name is a
602 // redefinition), push it as current DeclContext and try to continue parsing.
603 PushDeclContext(Namespc->getOriginalNamespace());
604 return Namespc;
605}
606
607/// ActOnFinishNamespaceDef - This callback is called after a namespace is
608/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
609void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
610 Decl *Dcl = static_cast<Decl *>(D);
611 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
612 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
613 Namespc->setRBracLoc(RBrace);
614 PopDeclContext();
615}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000616
617
618/// AddCXXDirectInitializerToDecl - This action is called immediately after
619/// ActOnDeclarator, when a C++ direct initializer is present.
620/// e.g: "int x(1);"
621void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
622 ExprTy **ExprTys, unsigned NumExprs,
623 SourceLocation *CommaLocs,
624 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000625 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000626 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000627
628 // If there is no declaration, there was an error parsing it. Just ignore
629 // the initializer.
630 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +0000631 for (unsigned i = 0; i != NumExprs; ++i)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000632 delete static_cast<Expr *>(ExprTys[i]);
633 return;
634 }
635
636 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
637 if (!VDecl) {
638 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
639 RealDecl->setInvalidDecl();
640 return;
641 }
642
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000643 // We will treat direct-initialization as a copy-initialization:
644 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000645 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
646 //
647 // Clients that want to distinguish between the two forms, can check for
648 // direct initializer using VarDecl::hasCXXDirectInitializer().
649 // A major benefit is that clients that don't particularly care about which
650 // exactly form was it (like the CodeGen) can handle both cases without
651 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000652
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000653 // C++ 8.5p11:
654 // The form of initialization (using parentheses or '=') is generally
655 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000656 // class type.
657
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000658 if (VDecl->getType()->isRecordType()) {
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000659 // FIXME: When constructors for class types are supported, determine how
660 // exactly semantic checking will be done for direct initializers.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +0000661 unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
662 "initialization for class types is not handled yet");
663 Diag(VDecl->getLocation(), DiagID);
664 RealDecl->setInvalidDecl();
665 return;
666 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000667
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000668 if (NumExprs > 1) {
669 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
670 SourceRange(VDecl->getLocation(), RParenLoc));
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000671 RealDecl->setInvalidDecl();
672 return;
673 }
674
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000675 // Let clients know that initialization was done with a direct initializer.
676 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +0000677
678 assert(NumExprs == 1 && "Expected 1 expression");
679 // Set the init expression, handles conversions.
680 AddInitializerToDecl(Dcl, ExprTys[0]);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000681}