1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Parse/DeclSpec.h"
21 #include "llvm/Support/Compiler.h"
23 using namespace clang
;
25 //===----------------------------------------------------------------------===//
26 // CheckDefaultArgumentVisitor
27 //===----------------------------------------------------------------------===//
30 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
31 /// the default argument of a parameter to determine whether it
32 /// contains any ill-formed subexpressions. For example, this will
33 /// diagnose the use of local variables or parameters within the
34 /// default argument expression.
35 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
36 : public StmtVisitor
<CheckDefaultArgumentVisitor
, bool> {
41 CheckDefaultArgumentVisitor(Expr
*defarg
, Sema
*s
)
42 : DefaultArg(defarg
), S(s
) {}
44 bool VisitExpr(Expr
*Node
);
45 bool VisitDeclRefExpr(DeclRefExpr
*DRE
);
48 /// VisitExpr - Visit all of the children of this expression.
49 bool CheckDefaultArgumentVisitor::VisitExpr(Expr
*Node
) {
50 bool IsInvalid
= false;
51 for (Stmt::child_iterator I
= Node
->child_begin(),
52 E
= Node
->child_end(); I
!= E
; ++I
)
53 IsInvalid
|= Visit(*I
);
57 /// VisitDeclRefExpr - Visit a reference to a declaration, to
58 /// determine whether this declaration can be used in the default
59 /// argument expression.
60 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr
*DRE
) {
61 ValueDecl
*Decl
= DRE
->getDecl();
62 if (ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(Decl
)) {
63 // C++ [dcl.fct.default]p9
64 // Default arguments are evaluated each time the function is
65 // called. The order of evaluation of function arguments is
66 // unspecified. Consequently, parameters of a function shall not
67 // be used in default argument expressions, even if they are not
68 // evaluated. Parameters of a function declared before a default
69 // argument expression are in scope and can hide namespace and
70 // class member names.
71 return S
->Diag(DRE
->getSourceRange().getBegin(),
72 diag::err_param_default_argument_references_param
,
73 Param
->getName(), DefaultArg
->getSourceRange());
74 } else if (VarDecl
*VDecl
= dyn_cast
<VarDecl
>(Decl
)) {
75 // C++ [dcl.fct.default]p7
76 // Local variables shall not be used in default argument
78 if (VDecl
->isBlockVarDecl())
79 return S
->Diag(DRE
->getSourceRange().getBegin(),
80 diag::err_param_default_argument_references_local
,
81 VDecl
->getName(), DefaultArg
->getSourceRange());
84 // FIXME: when Clang has support for member functions, "this"
85 // will also need to be diagnosed.
91 /// ActOnParamDefaultArgument - Check whether the default argument
92 /// provided for a function parameter is well-formed. If so, attach it
93 /// to the parameter declaration.
95 Sema::ActOnParamDefaultArgument(DeclTy
*param
, SourceLocation EqualLoc
,
97 ParmVarDecl
*Param
= (ParmVarDecl
*)param
;
98 llvm::OwningPtr
<Expr
> DefaultArg((Expr
*)defarg
);
99 QualType ParamType
= Param
->getType();
101 // Default arguments are only permitted in C++
102 if (!getLangOptions().CPlusPlus
) {
103 Diag(EqualLoc
, diag::err_param_default_argument
,
104 DefaultArg
->getSourceRange());
108 // C++ [dcl.fct.default]p5
109 // A default argument expression is implicitly converted (clause
110 // 4) to the parameter type. The default argument expression has
111 // the same semantic constraints as the initializer expression in
112 // a declaration of a variable of the parameter type, using the
113 // copy-initialization semantics (8.5).
115 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
116 // for C++ (since we want copy-initialization, not copy-assignment),
117 // but we don't have the right semantics implemented yet. Because of
118 // this, our error message is also very poor.
119 QualType DefaultArgType
= DefaultArg
->getType();
120 Expr
*DefaultArgPtr
= DefaultArg
.get();
121 AssignConvertType ConvTy
= CheckSingleAssignmentConstraints(ParamType
,
123 if (DefaultArgPtr
!= DefaultArg
.get()) {
125 DefaultArg
.reset(DefaultArgPtr
);
127 if (DiagnoseAssignmentResult(ConvTy
, DefaultArg
->getLocStart(),
128 ParamType
, DefaultArgType
, DefaultArg
.get(),
129 "in default argument")) {
133 // Check that the default argument is well-formed
134 CheckDefaultArgumentVisitor
DefaultArgChecker(DefaultArg
.get(), this);
135 if (DefaultArgChecker
.Visit(DefaultArg
.get()))
138 // Okay: add the default argument to the parameter
139 Param
->setDefaultArg(DefaultArg
.take());
142 /// CheckExtraCXXDefaultArguments - Check for any extra default
143 /// arguments in the declarator, which is not a function declaration
144 /// or definition and therefore is not permitted to have default
145 /// arguments. This routine should be invoked for every declarator
146 /// that is not a function declaration or definition.
147 void Sema::CheckExtraCXXDefaultArguments(Declarator
&D
) {
148 // C++ [dcl.fct.default]p3
149 // A default argument expression shall be specified only in the
150 // parameter-declaration-clause of a function declaration or in a
151 // template-parameter (14.1). It shall not be specified for a
152 // parameter pack. If it is specified in a
153 // parameter-declaration-clause, it shall not occur within a
154 // declarator or abstract-declarator of a parameter-declaration.
155 for (unsigned i
= 0; i
< D
.getNumTypeObjects(); ++i
) {
156 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
157 if (chunk
.Kind
== DeclaratorChunk::Function
) {
158 for (unsigned argIdx
= 0; argIdx
< chunk
.Fun
.NumArgs
; ++argIdx
) {
159 ParmVarDecl
*Param
= (ParmVarDecl
*)chunk
.Fun
.ArgInfo
[argIdx
].Param
;
160 if (Param
->getDefaultArg()) {
161 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
,
162 Param
->getDefaultArg()->getSourceRange());
163 Param
->setDefaultArg(0);
170 // MergeCXXFunctionDecl - Merge two declarations of the same C++
171 // function, once we already know that they have the same
172 // type. Subroutine of MergeFunctionDecl.
174 Sema::MergeCXXFunctionDecl(FunctionDecl
*New
, FunctionDecl
*Old
) {
175 // C++ [dcl.fct.default]p4:
177 // For non-template functions, default arguments can be added in
178 // later declarations of a function in the same
179 // scope. Declarations in different scopes have completely
180 // distinct sets of default arguments. That is, declarations in
181 // inner scopes do not acquire default arguments from
182 // declarations in outer scopes, and vice versa. In a given
183 // function declaration, all parameters subsequent to a
184 // parameter with a default argument shall have default
185 // arguments supplied in this or previous declarations. A
186 // default argument shall not be redefined by a later
187 // declaration (not even to the same value).
188 for (unsigned p
= 0, NumParams
= Old
->getNumParams(); p
< NumParams
; ++p
) {
189 ParmVarDecl
*OldParam
= Old
->getParamDecl(p
);
190 ParmVarDecl
*NewParam
= New
->getParamDecl(p
);
192 if(OldParam
->getDefaultArg() && NewParam
->getDefaultArg()) {
193 Diag(NewParam
->getLocation(),
194 diag::err_param_default_argument_redefinition
,
195 NewParam
->getDefaultArg()->getSourceRange());
196 Diag(OldParam
->getLocation(), diag::err_previous_definition
);
197 } else if (OldParam
->getDefaultArg()) {
198 // Merge the old default argument into the new parameter
199 NewParam
->setDefaultArg(OldParam
->getDefaultArg());
206 /// CheckCXXDefaultArguments - Verify that the default arguments for a
207 /// function declaration are well-formed according to C++
208 /// [dcl.fct.default].
209 void Sema::CheckCXXDefaultArguments(FunctionDecl
*FD
) {
210 unsigned NumParams
= FD
->getNumParams();
213 // Find first parameter with a default argument
214 for (p
= 0; p
< NumParams
; ++p
) {
215 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
216 if (Param
->getDefaultArg())
220 // C++ [dcl.fct.default]p4:
221 // In a given function declaration, all parameters
222 // subsequent to a parameter with a default argument shall
223 // have default arguments supplied in this or previous
224 // declarations. A default argument shall not be redefined
225 // by a later declaration (not even to the same value).
226 unsigned LastMissingDefaultArg
= 0;
227 for(; p
< NumParams
; ++p
) {
228 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
229 if (!Param
->getDefaultArg()) {
230 if (Param
->getIdentifier())
231 Diag(Param
->getLocation(),
232 diag::err_param_default_argument_missing_name
,
233 Param
->getIdentifier()->getName());
235 Diag(Param
->getLocation(),
236 diag::err_param_default_argument_missing
);
238 LastMissingDefaultArg
= p
;
242 if (LastMissingDefaultArg
> 0) {
243 // Some default arguments were missing. Clear out all of the
244 // default arguments up to (and including) the last missing
245 // default argument, so that we leave the function parameters
246 // in a semantically valid state.
247 for (p
= 0; p
<= LastMissingDefaultArg
; ++p
) {
248 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
249 if (Param
->getDefaultArg()) {
250 delete Param
->getDefaultArg();
251 Param
->setDefaultArg(0);
257 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
258 /// one entry in the base class list of a class specifier, for
260 /// class foo : public bar, virtual private baz {
261 /// 'public bar' and 'virtual private baz' are each base-specifiers.
262 void Sema::ActOnBaseSpecifier(DeclTy
*classdecl
, SourceRange SpecifierRange
,
263 bool Virtual
, AccessSpecifier Access
,
264 TypeTy
*basetype
, SourceLocation BaseLoc
) {
265 RecordDecl
*Decl
= (RecordDecl
*)classdecl
;
266 QualType BaseType
= Context
.getTypeDeclType((TypeDecl
*)basetype
);
268 // Base specifiers must be record types.
269 if (!BaseType
->isRecordType()) {
270 Diag(BaseLoc
, diag::err_base_must_be_class
, SpecifierRange
);
274 // C++ [class.union]p1:
275 // A union shall not be used as a base class.
276 if (BaseType
->isUnionType()) {
277 Diag(BaseLoc
, diag::err_union_as_base_class
, SpecifierRange
);
281 // C++ [class.union]p1:
282 // A union shall not have base classes.
283 if (Decl
->isUnion()) {
284 Diag(Decl
->getLocation(), diag::err_base_clause_on_union
,
286 Decl
->setInvalidDecl();
290 // C++ [class.derived]p2:
291 // The class-name in a base-specifier shall not be an incompletely
293 if (BaseType
->isIncompleteType()) {
294 Diag(BaseLoc
, diag::err_incomplete_base_class
, SpecifierRange
);
298 // FIXME: C++ [class.mi]p3:
299 // A class shall not be specified as a direct base class of a
300 // derived class more than once.
302 // FIXME: Attach base class to the record.
305 //===----------------------------------------------------------------------===//
306 // C++ class member Handling
307 //===----------------------------------------------------------------------===//
309 /// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
310 /// definition, when on C++.
311 void Sema::ActOnStartCXXClassDef(Scope
*S
, DeclTy
*D
, SourceLocation LBrace
) {
312 Decl
*Dcl
= static_cast<Decl
*>(D
);
313 PushDeclContext(cast
<CXXRecordDecl
>(Dcl
));
314 FieldCollector
->StartClass();
317 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
318 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
319 /// bitfield width if there is one and 'InitExpr' specifies the initializer if
320 /// any. 'LastInGroup' is non-null for cases where one declspec has multiple
321 /// declarators on it.
323 /// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
324 /// an instance field is declared, a new CXXFieldDecl is created but the method
325 /// does *not* return it; it returns LastInGroup instead. The other C++ members
326 /// (which are all ScopedDecls) are returned after appending them to
329 Sema::ActOnCXXMemberDeclarator(Scope
*S
, AccessSpecifier AS
, Declarator
&D
,
330 ExprTy
*BW
, ExprTy
*InitExpr
,
331 DeclTy
*LastInGroup
) {
332 const DeclSpec
&DS
= D
.getDeclSpec();
333 IdentifierInfo
*II
= D
.getIdentifier();
334 Expr
*BitWidth
= static_cast<Expr
*>(BW
);
335 Expr
*Init
= static_cast<Expr
*>(InitExpr
);
336 SourceLocation Loc
= D
.getIdentifierLoc();
338 // C++ 9.2p6: A member shall not be declared to have automatic storage
339 // duration (auto, register) or with the extern storage-class-specifier.
340 switch (DS
.getStorageClassSpec()) {
341 case DeclSpec::SCS_unspecified
:
342 case DeclSpec::SCS_typedef
:
343 case DeclSpec::SCS_static
:
347 if (DS
.getStorageClassSpecLoc().isValid())
348 Diag(DS
.getStorageClassSpecLoc(),
349 diag::err_storageclass_invalid_for_member
);
351 Diag(DS
.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member
);
352 D
.getMutableDeclSpec().ClearStorageClassSpecs();
355 QualType T
= GetTypeForDeclarator(D
, S
);
357 // T->isFunctionType() is used instead of D.isFunctionDeclarator() to cover
362 bool isInstField
= (DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
&&
363 !T
->isFunctionType());
366 bool InvalidDecl
= false;
369 Member
= static_cast<Decl
*>(ActOnField(S
, Loc
, D
, BitWidth
));
371 Member
= static_cast<Decl
*>(ActOnDeclarator(S
, D
, LastInGroup
));
373 if (!Member
) return LastInGroup
;
375 assert(II
|| isInstField
&& "No identifier for non-field ?");
377 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
378 // specific methods. Use a wrapper class that can be used with all C++ class
380 CXXClassMemberWrapper(Member
).setAccess(AS
);
383 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
384 // constant-expression be a value equal to zero.
385 // FIXME: Check this.
387 if (D
.isFunctionDeclarator()) {
388 // FIXME: Emit diagnostic about only constructors taking base initializers
389 // or something similar, when constructor support is in place.
390 Diag(Loc
, diag::err_not_bitfield_type
,
391 II
->getName(), BitWidth
->getSourceRange());
394 } else if (isInstField
|| isa
<FunctionDecl
>(Member
)) {
395 // An instance field or a function typedef ("typedef int f(); f a;").
396 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
397 if (!T
->isIntegralType()) {
398 Diag(Loc
, diag::err_not_integral_type_bitfield
,
399 II
->getName(), BitWidth
->getSourceRange());
403 } else if (isa
<TypedefDecl
>(Member
)) {
404 // "cannot declare 'A' to be a bit-field type"
405 Diag(Loc
, diag::err_not_bitfield_type
, II
->getName(),
406 BitWidth
->getSourceRange());
410 assert(isa
<CXXClassVarDecl
>(Member
) &&
411 "Didn't we cover all member kinds?");
412 // C++ 9.6p3: A bit-field shall not be a static member.
413 // "static member 'A' cannot be a bit-field"
414 Diag(Loc
, diag::err_static_not_bitfield
, II
->getName(),
415 BitWidth
->getSourceRange());
421 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
422 // if it declares a static member of const integral or const enumeration
424 if (CXXClassVarDecl
*CVD
= dyn_cast
<CXXClassVarDecl
>(Member
)) {
425 // ...static member of...
427 // ...const integral or const enumeration type.
428 if (Context
.getCanonicalType(CVD
->getType()).isConstQualified() &&
429 CVD
->getType()->isIntegralType()) {
430 // constant-initializer
431 if (CheckForConstantInitializer(Init
, CVD
->getType()))
435 // not const integral.
436 Diag(Loc
, diag::err_member_initialization
,
437 II
->getName(), Init
->getSourceRange());
442 // not static member.
443 Diag(Loc
, diag::err_member_initialization
,
444 II
->getName(), Init
->getSourceRange());
450 Member
->setInvalidDecl();
453 FieldCollector
->Add(cast
<CXXFieldDecl
>(Member
));
459 void Sema::ActOnFinishCXXMemberSpecification(Scope
* S
, SourceLocation RLoc
,
461 SourceLocation LBrac
,
462 SourceLocation RBrac
) {
463 ActOnFields(S
, RLoc
, TagDecl
,
464 (DeclTy
**)FieldCollector
->getCurFields(),
465 FieldCollector
->getCurNumFields(), LBrac
, RBrac
, 0);
468 void Sema::ActOnFinishCXXClassDef(DeclTy
*D
) {
469 CXXRecordDecl
*Rec
= cast
<CXXRecordDecl
>(static_cast<Decl
*>(D
));
470 FieldCollector
->FinishClass();
473 // Everything, including inline method definitions, have been parsed.
474 // Let the consumer know of the new TagDecl definition.
475 Consumer
.HandleTagDeclDefinition(Rec
);
478 //===----------------------------------------------------------------------===//
479 // Namespace Handling
480 //===----------------------------------------------------------------------===//
482 /// ActOnStartNamespaceDef - This is called at the start of a namespace
484 Sema::DeclTy
*Sema::ActOnStartNamespaceDef(Scope
*NamespcScope
,
485 SourceLocation IdentLoc
,
487 SourceLocation LBrace
) {
488 NamespaceDecl
*Namespc
=
489 NamespaceDecl::Create(Context
, CurContext
, IdentLoc
, II
);
490 Namespc
->setLBracLoc(LBrace
);
492 Scope
*DeclRegionScope
= NamespcScope
->getParent();
495 // C++ [namespace.def]p2:
496 // The identifier in an original-namespace-definition shall not have been
497 // previously defined in the declarative region in which the
498 // original-namespace-definition appears. The identifier in an
499 // original-namespace-definition is the name of the namespace. Subsequently
500 // in that declarative region, it is treated as an original-namespace-name.
503 LookupDecl(II
, Decl::IDNS_Tag
| Decl::IDNS_Ordinary
, DeclRegionScope
,
504 /*enableLazyBuiltinCreation=*/false);
506 if (PrevDecl
&& isDeclInScope(PrevDecl
, CurContext
, DeclRegionScope
)) {
507 if (NamespaceDecl
*OrigNS
= dyn_cast
<NamespaceDecl
>(PrevDecl
)) {
508 // This is an extended namespace definition.
509 // Attach this namespace decl to the chain of extended namespace
511 NamespaceDecl
*NextNS
= OrigNS
;
512 while (NextNS
->getNextNamespace())
513 NextNS
= NextNS
->getNextNamespace();
515 NextNS
->setNextNamespace(Namespc
);
516 Namespc
->setOriginalNamespace(OrigNS
);
518 // We won't add this decl to the current scope. We want the namespace
519 // name to return the original namespace decl during a name lookup.
521 // This is an invalid name redefinition.
522 Diag(Namespc
->getLocation(), diag::err_redefinition_different_kind
,
524 Diag(PrevDecl
->getLocation(), diag::err_previous_definition
);
525 Namespc
->setInvalidDecl();
526 // Continue on to push Namespc as current DeclContext and return it.
529 // This namespace name is declared for the first time.
530 PushOnScopeChains(Namespc
, DeclRegionScope
);
534 // FIXME: Handle anonymous namespaces
537 // Although we could have an invalid decl (i.e. the namespace name is a
538 // redefinition), push it as current DeclContext and try to continue parsing.
539 PushDeclContext(Namespc
->getOriginalNamespace());
543 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
544 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
545 void Sema::ActOnFinishNamespaceDef(DeclTy
*D
, SourceLocation RBrace
) {
546 Decl
*Dcl
= static_cast<Decl
*>(D
);
547 NamespaceDecl
*Namespc
= dyn_cast_or_null
<NamespaceDecl
>(Dcl
);
548 assert(Namespc
&& "Invalid parameter, expected NamespaceDecl");
549 Namespc
->setRBracLoc(RBrace
);
554 /// AddCXXDirectInitializerToDecl - This action is called immediately after
555 /// ActOnDeclarator, when a C++ direct initializer is present.
557 void Sema::AddCXXDirectInitializerToDecl(DeclTy
*Dcl
, SourceLocation LParenLoc
,
558 ExprTy
**ExprTys
, unsigned NumExprs
,
559 SourceLocation
*CommaLocs
,
560 SourceLocation RParenLoc
) {
561 assert(NumExprs
!= 0 && ExprTys
&& "missing expressions");
562 Decl
*RealDecl
= static_cast<Decl
*>(Dcl
);
564 // If there is no declaration, there was an error parsing it. Just ignore
567 for (unsigned i
= 0; i
!= NumExprs
; ++i
)
568 delete static_cast<Expr
*>(ExprTys
[i
]);
572 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
574 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
575 RealDecl
->setInvalidDecl();
579 // We will treat direct-initialization as a copy-initialization:
580 // int x(1); -as-> int x = 1;
581 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
583 // Clients that want to distinguish between the two forms, can check for
584 // direct initializer using VarDecl::hasCXXDirectInitializer().
585 // A major benefit is that clients that don't particularly care about which
586 // exactly form was it (like the CodeGen) can handle both cases without
587 // special case code.
590 // The form of initialization (using parentheses or '=') is generally
591 // insignificant, but does matter when the entity being initialized has a
594 if (VDecl
->getType()->isRecordType()) {
595 // FIXME: When constructors for class types are supported, determine how
596 // exactly semantic checking will be done for direct initializers.
597 unsigned DiagID
= PP
.getDiagnostics().getCustomDiagID(Diagnostic::Error
,
598 "initialization for class types is not handled yet");
599 Diag(VDecl
->getLocation(), DiagID
);
600 RealDecl
->setInvalidDecl();
605 Diag(CommaLocs
[0], diag::err_builtin_direct_init_more_than_one_arg
,
606 SourceRange(VDecl
->getLocation(), RParenLoc
));
607 RealDecl
->setInvalidDecl();
611 // Let clients know that initialization was done with a direct initializer.
612 VDecl
->setCXXDirectInitializer(true);
614 assert(NumExprs
== 1 && "Expected 1 expression");
615 // Set the init expression, handles conversions.
616 AddInitializerToDecl(Dcl
, ExprTys
[0]);