blob: 9d99494532b4a1b6b601fa3771a74709e92a3cc1 [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"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000018#include "clang/Basic/Diagnostic.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000019#include "clang/Parse/DeclSpec.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "llvm/Support/Compiler.h"
Chris Lattner3d1cee32008-04-08 05:04:30 +000021
22using namespace clang;
23
Chris Lattner8123a952008-04-10 02:22:51 +000024//===----------------------------------------------------------------------===//
25// CheckDefaultArgumentVisitor
26//===----------------------------------------------------------------------===//
27
Chris Lattner9e979552008-04-12 23:52:44 +000028namespace {
29 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
30 /// the default argument of a parameter to determine whether it
31 /// contains any ill-formed subexpressions. For example, this will
32 /// diagnose the use of local variables or parameters within the
33 /// default argument expression.
34 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000035 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000036 Expr *DefaultArg;
37 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000038
Chris Lattner9e979552008-04-12 23:52:44 +000039 public:
40 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
41 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000042
Chris Lattner9e979552008-04-12 23:52:44 +000043 bool VisitExpr(Expr *Node);
44 bool VisitDeclRefExpr(DeclRefExpr *DRE);
45 };
Chris Lattner8123a952008-04-10 02:22:51 +000046
Chris Lattner9e979552008-04-12 23:52:44 +000047 /// VisitExpr - Visit all of the children of this expression.
48 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
49 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000050 for (Stmt::child_iterator I = Node->child_begin(),
51 E = Node->child_end(); I != E; ++I)
52 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000053 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000054 }
55
Chris Lattner9e979552008-04-12 23:52:44 +000056 /// VisitDeclRefExpr - Visit a reference to a declaration, to
57 /// determine whether this declaration can be used in the default
58 /// argument expression.
59 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
60 ValueDecl *Decl = DRE->getDecl();
61 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
62 // C++ [dcl.fct.default]p9
63 // Default arguments are evaluated each time the function is
64 // called. The order of evaluation of function arguments is
65 // unspecified. Consequently, parameters of a function shall not
66 // be used in default argument expressions, even if they are not
67 // evaluated. Parameters of a function declared before a default
68 // argument expression are in scope and can hide namespace and
69 // class member names.
70 return S->Diag(DRE->getSourceRange().getBegin(),
71 diag::err_param_default_argument_references_param,
72 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff248a7532008-04-15 22:42:06 +000073 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000074 // C++ [dcl.fct.default]p7
75 // Local variables shall not be used in default argument
76 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000077 if (VDecl->isBlockVarDecl())
78 return S->Diag(DRE->getSourceRange().getBegin(),
79 diag::err_param_default_argument_references_local,
80 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattner9e979552008-04-12 23:52:44 +000081 }
Chris Lattner8123a952008-04-10 02:22:51 +000082
Chris Lattner9e979552008-04-12 23:52:44 +000083 // FIXME: when Clang has support for member functions, "this"
84 // will also need to be diagnosed.
85
86 return false;
87 }
Chris Lattner8123a952008-04-10 02:22:51 +000088}
89
90/// ActOnParamDefaultArgument - Check whether the default argument
91/// provided for a function parameter is well-formed. If so, attach it
92/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +000093void
94Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
95 ExprTy *defarg) {
96 ParmVarDecl *Param = (ParmVarDecl *)param;
97 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
98 QualType ParamType = Param->getType();
99
100 // Default arguments are only permitted in C++
101 if (!getLangOptions().CPlusPlus) {
102 Diag(EqualLoc, diag::err_param_default_argument,
103 DefaultArg->getSourceRange());
104 return;
105 }
106
107 // C++ [dcl.fct.default]p5
108 // A default argument expression is implicitly converted (clause
109 // 4) to the parameter type. The default argument expression has
110 // the same semantic constraints as the initializer expression in
111 // a declaration of a variable of the parameter type, using the
112 // copy-initialization semantics (8.5).
113 //
114 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
115 // for C++ (since we want copy-initialization, not copy-assignment),
116 // but we don't have the right semantics implemented yet. Because of
117 // this, our error message is also very poor.
118 QualType DefaultArgType = DefaultArg->getType();
119 Expr *DefaultArgPtr = DefaultArg.get();
120 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
121 DefaultArgPtr);
122 if (DefaultArgPtr != DefaultArg.get()) {
123 DefaultArg.take();
124 DefaultArg.reset(DefaultArgPtr);
125 }
126 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
127 ParamType, DefaultArgType, DefaultArg.get(),
128 "in default argument")) {
129 return;
130 }
131
Chris Lattner8123a952008-04-10 02:22:51 +0000132 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000133 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner8123a952008-04-10 02:22:51 +0000134 if (DefaultArgChecker.Visit(DefaultArg.get()))
135 return;
136
Chris Lattner3d1cee32008-04-08 05:04:30 +0000137 // Okay: add the default argument to the parameter
138 Param->setDefaultArg(DefaultArg.take());
139}
140
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000141/// CheckExtraCXXDefaultArguments - Check for any extra default
142/// arguments in the declarator, which is not a function declaration
143/// or definition and therefore is not permitted to have default
144/// arguments. This routine should be invoked for every declarator
145/// that is not a function declaration or definition.
146void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
147 // C++ [dcl.fct.default]p3
148 // A default argument expression shall be specified only in the
149 // parameter-declaration-clause of a function declaration or in a
150 // template-parameter (14.1). It shall not be specified for a
151 // parameter pack. If it is specified in a
152 // parameter-declaration-clause, it shall not occur within a
153 // declarator or abstract-declarator of a parameter-declaration.
154 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
155 DeclaratorChunk &chunk = D.getTypeObject(i);
156 if (chunk.Kind == DeclaratorChunk::Function) {
157 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
158 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
159 if (Param->getDefaultArg()) {
160 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
161 Param->getDefaultArg()->getSourceRange());
162 Param->setDefaultArg(0);
163 }
164 }
165 }
166 }
167}
168
Chris Lattner3d1cee32008-04-08 05:04:30 +0000169// MergeCXXFunctionDecl - Merge two declarations of the same C++
170// function, once we already know that they have the same
171// type. Subroutine of MergeFunctionDecl.
172FunctionDecl *
173Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
174 // C++ [dcl.fct.default]p4:
175 //
176 // For non-template functions, default arguments can be added in
177 // later declarations of a function in the same
178 // scope. Declarations in different scopes have completely
179 // distinct sets of default arguments. That is, declarations in
180 // inner scopes do not acquire default arguments from
181 // declarations in outer scopes, and vice versa. In a given
182 // function declaration, all parameters subsequent to a
183 // parameter with a default argument shall have default
184 // arguments supplied in this or previous declarations. A
185 // default argument shall not be redefined by a later
186 // declaration (not even to the same value).
187 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
188 ParmVarDecl *OldParam = Old->getParamDecl(p);
189 ParmVarDecl *NewParam = New->getParamDecl(p);
190
191 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
192 Diag(NewParam->getLocation(),
193 diag::err_param_default_argument_redefinition,
194 NewParam->getDefaultArg()->getSourceRange());
195 Diag(OldParam->getLocation(), diag::err_previous_definition);
196 } else if (OldParam->getDefaultArg()) {
197 // Merge the old default argument into the new parameter
198 NewParam->setDefaultArg(OldParam->getDefaultArg());
199 }
200 }
201
202 return New;
203}
204
205/// CheckCXXDefaultArguments - Verify that the default arguments for a
206/// function declaration are well-formed according to C++
207/// [dcl.fct.default].
208void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
209 unsigned NumParams = FD->getNumParams();
210 unsigned p;
211
212 // Find first parameter with a default argument
213 for (p = 0; p < NumParams; ++p) {
214 ParmVarDecl *Param = FD->getParamDecl(p);
215 if (Param->getDefaultArg())
216 break;
217 }
218
219 // C++ [dcl.fct.default]p4:
220 // In a given function declaration, all parameters
221 // subsequent to a parameter with a default argument shall
222 // have default arguments supplied in this or previous
223 // declarations. A default argument shall not be redefined
224 // by a later declaration (not even to the same value).
225 unsigned LastMissingDefaultArg = 0;
226 for(; p < NumParams; ++p) {
227 ParmVarDecl *Param = FD->getParamDecl(p);
228 if (!Param->getDefaultArg()) {
229 if (Param->getIdentifier())
230 Diag(Param->getLocation(),
231 diag::err_param_default_argument_missing_name,
232 Param->getIdentifier()->getName());
233 else
234 Diag(Param->getLocation(),
235 diag::err_param_default_argument_missing);
236
237 LastMissingDefaultArg = p;
238 }
239 }
240
241 if (LastMissingDefaultArg > 0) {
242 // Some default arguments were missing. Clear out all of the
243 // default arguments up to (and including) the last missing
244 // default argument, so that we leave the function parameters
245 // in a semantically valid state.
246 for (p = 0; p <= LastMissingDefaultArg; ++p) {
247 ParmVarDecl *Param = FD->getParamDecl(p);
248 if (Param->getDefaultArg()) {
249 delete Param->getDefaultArg();
250 Param->setDefaultArg(0);
251 }
252 }
253 }
254}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000255
256/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
257/// one entry in the base class list of a class specifier, for
258/// example:
259/// class foo : public bar, virtual private baz {
260/// 'public bar' and 'virtual private baz' are each base-specifiers.
261void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
262 bool Virtual, AccessSpecifier Access,
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +0000263 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000264 RecordDecl *Decl = (RecordDecl*)classdecl;
265 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
266
267 // Base specifiers must be record types.
268 if (!BaseType->isRecordType()) {
269 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
270 return;
271 }
272
273 // C++ [class.union]p1:
274 // A union shall not be used as a base class.
275 if (BaseType->isUnionType()) {
276 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
277 return;
278 }
279
280 // C++ [class.union]p1:
281 // A union shall not have base classes.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000282 if (Decl->isUnion()) {
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000283 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
284 SpecifierRange);
285 Decl->setInvalidDecl();
286 return;
287 }
288
289 // C++ [class.derived]p2:
290 // The class-name in a base-specifier shall not be an incompletely
291 // defined class.
292 if (BaseType->isIncompleteType()) {
293 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
294 return;
295 }
296
297 // FIXME: C++ [class.mi]p3:
298 // A class shall not be specified as a direct base class of a
299 // derived class more than once.
300
301 // FIXME: Attach base class to the record.
302}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000303
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000304//===----------------------------------------------------------------------===//
305// C++ class member Handling
306//===----------------------------------------------------------------------===//
307
308/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
309/// definition, when on C++.
310void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
311 Decl *Dcl = static_cast<Decl *>(D);
312 PushDeclContext(cast<CXXRecordDecl>(Dcl));
313 FieldCollector->StartClass();
314}
315
316/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
317/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
318/// bitfield width if there is one and 'InitExpr' specifies the initializer if
319/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
320/// declarators on it.
321///
322/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
323/// an instance field is declared, a new CXXFieldDecl is created but the method
324/// does *not* return it; it returns LastInGroup instead. The other C++ members
325/// (which are all ScopedDecls) are returned after appending them to
326/// LastInGroup.
327Sema::DeclTy *
328Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
329 ExprTy *BW, ExprTy *InitExpr,
330 DeclTy *LastInGroup) {
331 const DeclSpec &DS = D.getDeclSpec();
332 IdentifierInfo *II = D.getIdentifier();
333 Expr *BitWidth = static_cast<Expr*>(BW);
334 Expr *Init = static_cast<Expr*>(InitExpr);
335 SourceLocation Loc = D.getIdentifierLoc();
336
337 // C++ 9.2p6: A member shall not be declared to have automatic storage
338 // duration (auto, register) or with the extern storage-class-specifier.
339 switch (DS.getStorageClassSpec()) {
340 case DeclSpec::SCS_unspecified:
341 case DeclSpec::SCS_typedef:
342 case DeclSpec::SCS_static:
343 // FALL THROUGH.
344 break;
345 default:
346 if (DS.getStorageClassSpecLoc().isValid())
347 Diag(DS.getStorageClassSpecLoc(),
348 diag::err_storageclass_invalid_for_member);
349 else
350 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
351 D.getMutableDeclSpec().ClearStorageClassSpecs();
352 }
353
354 QualType T = GetTypeForDeclarator(D, S);
355
356 // T->isFunctionType() is used instead of D.isFunctionDeclarator() to cover
357 // this case:
358 //
359 // typedef int f();
360 // f a;
361 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
362 !T->isFunctionType());
363
364 Decl *Member;
365 bool InvalidDecl = false;
366
367 if (isInstField)
368 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
369 else
Daniel Dunbar914701e2008-08-05 16:28:08 +0000370 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000371
372 if (!Member) return LastInGroup;
373
374 assert(II || isInstField && "No identifier for non-field ?");
375
376 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
377 // specific methods. Use a wrapper class that can be used with all C++ class
378 // member decls.
379 CXXClassMemberWrapper(Member).setAccess(AS);
380
381 if (BitWidth) {
382 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
383 // constant-expression be a value equal to zero.
384 // FIXME: Check this.
385
386 if (D.isFunctionDeclarator()) {
387 // FIXME: Emit diagnostic about only constructors taking base initializers
388 // or something similar, when constructor support is in place.
389 Diag(Loc, diag::err_not_bitfield_type,
390 II->getName(), BitWidth->getSourceRange());
391 InvalidDecl = true;
392
393 } else if (isInstField || isa<FunctionDecl>(Member)) {
394 // An instance field or a function typedef ("typedef int f(); f a;").
395 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
396 if (!T->isIntegralType()) {
397 Diag(Loc, diag::err_not_integral_type_bitfield,
398 II->getName(), BitWidth->getSourceRange());
399 InvalidDecl = true;
400 }
401
402 } else if (isa<TypedefDecl>(Member)) {
403 // "cannot declare 'A' to be a bit-field type"
404 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
405 BitWidth->getSourceRange());
406 InvalidDecl = true;
407
408 } else {
409 assert(isa<CXXClassVarDecl>(Member) &&
410 "Didn't we cover all member kinds?");
411 // C++ 9.6p3: A bit-field shall not be a static member.
412 // "static member 'A' cannot be a bit-field"
413 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
414 BitWidth->getSourceRange());
415 InvalidDecl = true;
416 }
417 }
418
419 if (Init) {
420 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
421 // if it declares a static member of const integral or const enumeration
422 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000423 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
424 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000425 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000426 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000427 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
428 CVD->getType()->isIntegralType()) {
429 // constant-initializer
430 if (CheckForConstantInitializer(Init, CVD->getType()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000431 InvalidDecl = true;
432
433 } else {
434 // not const integral.
435 Diag(Loc, diag::err_member_initialization,
436 II->getName(), Init->getSourceRange());
437 InvalidDecl = true;
438 }
439
440 } else {
441 // not static member.
442 Diag(Loc, diag::err_member_initialization,
443 II->getName(), Init->getSourceRange());
444 InvalidDecl = true;
445 }
446 }
447
448 if (InvalidDecl)
449 Member->setInvalidDecl();
450
451 if (isInstField) {
452 FieldCollector->Add(cast<CXXFieldDecl>(Member));
453 return LastInGroup;
454 }
455 return Member;
456}
457
458void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
459 DeclTy *TagDecl,
460 SourceLocation LBrac,
461 SourceLocation RBrac) {
462 ActOnFields(S, RLoc, TagDecl,
463 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000464 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000465}
466
Argyrios Kyrtzidis5b7f0c82008-08-09 00:39:29 +0000467void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000468 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000469 FieldCollector->FinishClass();
470 PopDeclContext();
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +0000471
472 // Everything, including inline method definitions, have been parsed.
473 // Let the consumer know of the new TagDecl definition.
474 Consumer.HandleTagDeclDefinition(Rec);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000475}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000476
477//===----------------------------------------------------------------------===//
478// Namespace Handling
479//===----------------------------------------------------------------------===//
480
481/// ActOnStartNamespaceDef - This is called at the start of a namespace
482/// definition.
483Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
484 SourceLocation IdentLoc,
485 IdentifierInfo *II,
486 SourceLocation LBrace) {
487 NamespaceDecl *Namespc =
488 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
489 Namespc->setLBracLoc(LBrace);
490
491 Scope *DeclRegionScope = NamespcScope->getParent();
492
493 if (II) {
494 // C++ [namespace.def]p2:
495 // The identifier in an original-namespace-definition shall not have been
496 // previously defined in the declarative region in which the
497 // original-namespace-definition appears. The identifier in an
498 // original-namespace-definition is the name of the namespace. Subsequently
499 // in that declarative region, it is treated as an original-namespace-name.
500
501 Decl *PrevDecl =
502 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
503 /*enableLazyBuiltinCreation=*/false);
504
Argyrios Kyrtzidis2fac6262008-09-10 02:11:07 +0000505 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000506 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
507 // This is an extended namespace definition.
508 // Attach this namespace decl to the chain of extended namespace
509 // definitions.
510 NamespaceDecl *NextNS = OrigNS;
511 while (NextNS->getNextNamespace())
512 NextNS = NextNS->getNextNamespace();
513
514 NextNS->setNextNamespace(Namespc);
515 Namespc->setOriginalNamespace(OrigNS);
516
517 // We won't add this decl to the current scope. We want the namespace
518 // name to return the original namespace decl during a name lookup.
519 } else {
520 // This is an invalid name redefinition.
521 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
522 Namespc->getName());
523 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
524 Namespc->setInvalidDecl();
525 // Continue on to push Namespc as current DeclContext and return it.
526 }
527 } else {
528 // This namespace name is declared for the first time.
529 PushOnScopeChains(Namespc, DeclRegionScope);
530 }
531 }
532 else {
533 // FIXME: Handle anonymous namespaces
534 }
535
536 // Although we could have an invalid decl (i.e. the namespace name is a
537 // redefinition), push it as current DeclContext and try to continue parsing.
538 PushDeclContext(Namespc->getOriginalNamespace());
539 return Namespc;
540}
541
542/// ActOnFinishNamespaceDef - This callback is called after a namespace is
543/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
544void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
545 Decl *Dcl = static_cast<Decl *>(D);
546 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
547 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
548 Namespc->setRBracLoc(RBrace);
549 PopDeclContext();
550}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +0000551
552
553/// AddCXXDirectInitializerToDecl - This action is called immediately after
554/// ActOnDeclarator, when a C++ direct initializer is present.
555/// e.g: "int x(1);"
556void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
557 ExprTy **ExprTys, unsigned NumExprs,
558 SourceLocation *CommaLocs,
559 SourceLocation RParenLoc) {
560 Decl *RealDecl = static_cast<Decl *>(Dcl);
561 assert(NumExprs != 0 && ExprTys && "missing expressions");
562
563 // If there is no declaration, there was an error parsing it. Just ignore
564 // the initializer.
565 if (RealDecl == 0) {
566 for (int i=0; i != NumExprs; ++i)
567 delete static_cast<Expr *>(ExprTys[i]);
568 return;
569 }
570
571 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
572 if (!VDecl) {
573 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
574 RealDecl->setInvalidDecl();
575 return;
576 }
577
578 // We will treat direct-initialization as a copy-initialization with a
579 // type-construction expression of the variable's type. In plain english:
580 // We will treat:
581 // int x(1); -as-> int x = int(1);
582 // and for class types:
583 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
584 //
585 // Clients that want to distinguish between the two forms, can check for
586 // direct initializer using VarDecl::hasCXXDirectInitializer().
587 // A major benefit is that clients that don't particularly care about which
588 // exactly form was it (like the CodeGen) can handle both cases without
589 // special case code.
590 //
591 // According to the C++ standard, there shouldn't be semantic differences
592 // between a direct-initialization and a copy-initialization where the
593 // destination type is the same as the source type:
594 //
595 // C++ 8.5p11:
596 // The form of initialization (using parentheses or '=') is generally
597 // insignificant, but does matter when the entity being initialized has a
598 // class type; see below.
599 // C++ 8.5p15:
600 // [...]
601 // If the initialization is direct-initialization, or if it is
602 // copy-initialization where the cv-unqualified version of the source type is
603 // the same class as, or a derived class of, the class of the destination,
604 // constructors are considered. The applicable constructors are enumerated
605 // (13.3.1.3), and the best one is chosen through overload resolution (13.3).
606 // The constructor so selected is called to initialize the object, with the
607 // initializer expression(s) as its argument(s). If no constructor applies, or
608 // the overload resolution is ambiguous, the initialization is ill-formed.
609 // [...]
610 //
611 // Note that according to C++ 8.5p15, the same semantic process is applied
612 // to both the direct-initialization and copy-initialization,
613 // if destination type == source type.
614
615 // Get an expression for constructing the type of the variable, using the
616 // expression list of the initializer.
617 ExprResult Res = ActOnCXXTypeConstructExpr(VDecl->getLocation(),
618 VDecl->getType().getAsOpaquePtr(),
619 LParenLoc, ExprTys, NumExprs,
620 CommaLocs, RParenLoc);
621 if (Res.isInvalid) {
622 RealDecl->setInvalidDecl();
623 return;
624 }
625
626 // Performs additional semantic checks.
627 AddInitializerToDecl(Dcl, Res.Val);
628 // Let clients know that initialization was done with a direct initializer.
629 VDecl->setCXXDirectInitializer(true);
630}