blob: 827c737ad4ac2e0e7d190f838ddec5e24513d8e8 [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"
15#include "clang/Basic/LangOptions.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Chris Lattnerac7b83a2008-04-08 05:04:30 +000017#include "clang/AST/Expr.h"
Chris Lattner97316c02008-04-10 02:22:51 +000018#include "clang/AST/StmtVisitor.h"
Chris Lattnerac7b83a2008-04-08 05:04:30 +000019#include "clang/AST/Type.h"
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +000020#include "clang/Parse/Scope.h"
Chris Lattnerac7b83a2008-04-08 05:04:30 +000021#include "llvm/ADT/OwningPtr.h"
Chris Lattner97316c02008-04-10 02:22:51 +000022#include "llvm/Support/Compiler.h"
Chris Lattnerac7b83a2008-04-08 05:04:30 +000023
24using namespace clang;
25
Chris Lattner97316c02008-04-10 02:22:51 +000026//===----------------------------------------------------------------------===//
27// CheckDefaultArgumentVisitor
28//===----------------------------------------------------------------------===//
29
Chris Lattnerb1856db2008-04-12 23:52:44 +000030namespace {
31 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
32 /// the default argument of a parameter to determine whether it
33 /// contains any ill-formed subexpressions. For example, this will
34 /// diagnose the use of local variables or parameters within the
35 /// default argument expression.
36 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
37 : public StmtVisitor<CheckDefaultArgumentVisitor, bool>
38 {
39 Expr *DefaultArg;
40 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000041
Chris Lattnerb1856db2008-04-12 23:52:44 +000042 public:
43 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
44 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000045
Chris Lattnerb1856db2008-04-12 23:52:44 +000046 bool VisitExpr(Expr *Node);
47 bool VisitDeclRefExpr(DeclRefExpr *DRE);
48 };
Chris Lattner97316c02008-04-10 02:22:51 +000049
Chris Lattnerb1856db2008-04-12 23:52:44 +000050 /// VisitExpr - Visit all of the children of this expression.
51 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
52 bool IsInvalid = false;
53 for (Stmt::child_iterator first = Node->child_begin(),
54 last = Node->child_end();
55 first != last; ++first)
56 IsInvalid |= Visit(*first);
Chris Lattner97316c02008-04-10 02:22:51 +000057
Chris Lattnerb1856db2008-04-12 23:52:44 +000058 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000059 }
60
Chris Lattnerb1856db2008-04-12 23:52:44 +000061 /// VisitDeclRefExpr - Visit a reference to a declaration, to
62 /// determine whether this declaration can be used in the default
63 /// argument expression.
64 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
65 ValueDecl *Decl = DRE->getDecl();
66 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
67 // C++ [dcl.fct.default]p9
68 // Default arguments are evaluated each time the function is
69 // called. The order of evaluation of function arguments is
70 // unspecified. Consequently, parameters of a function shall not
71 // be used in default argument expressions, even if they are not
72 // evaluated. Parameters of a function declared before a default
73 // argument expression are in scope and can hide namespace and
74 // class member names.
75 return S->Diag(DRE->getSourceRange().getBegin(),
76 diag::err_param_default_argument_references_param,
77 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000078 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000079 // C++ [dcl.fct.default]p7
80 // Local variables shall not be used in default argument
81 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000082 if (VDecl->isBlockVarDecl())
83 return S->Diag(DRE->getSourceRange().getBegin(),
84 diag::err_param_default_argument_references_local,
85 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000086 }
Chris Lattner97316c02008-04-10 02:22:51 +000087
Chris Lattnerb1856db2008-04-12 23:52:44 +000088 // FIXME: when Clang has support for member functions, "this"
89 // will also need to be diagnosed.
90
91 return false;
92 }
Chris Lattner97316c02008-04-10 02:22:51 +000093}
94
95/// ActOnParamDefaultArgument - Check whether the default argument
96/// provided for a function parameter is well-formed. If so, attach it
97/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +000098void
99Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
100 ExprTy *defarg) {
101 ParmVarDecl *Param = (ParmVarDecl *)param;
102 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
103 QualType ParamType = Param->getType();
104
105 // Default arguments are only permitted in C++
106 if (!getLangOptions().CPlusPlus) {
107 Diag(EqualLoc, diag::err_param_default_argument,
108 DefaultArg->getSourceRange());
109 return;
110 }
111
112 // C++ [dcl.fct.default]p5
113 // A default argument expression is implicitly converted (clause
114 // 4) to the parameter type. The default argument expression has
115 // the same semantic constraints as the initializer expression in
116 // a declaration of a variable of the parameter type, using the
117 // copy-initialization semantics (8.5).
118 //
119 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
120 // for C++ (since we want copy-initialization, not copy-assignment),
121 // but we don't have the right semantics implemented yet. Because of
122 // this, our error message is also very poor.
123 QualType DefaultArgType = DefaultArg->getType();
124 Expr *DefaultArgPtr = DefaultArg.get();
125 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
126 DefaultArgPtr);
127 if (DefaultArgPtr != DefaultArg.get()) {
128 DefaultArg.take();
129 DefaultArg.reset(DefaultArgPtr);
130 }
131 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
132 ParamType, DefaultArgType, DefaultArg.get(),
133 "in default argument")) {
134 return;
135 }
136
137 // FIXME: C++ [dcl.fct.default]p3
138 // A default argument expression shall be specified only in the
139 // parameter-declaration-clause of a function declaration or in a
140 // template-parameter (14.1). It shall not be specified for a
141 // parameter pack. If it is specified in a
142 // parameter-declaration-clause, it shall not occur within a
143 // declarator or abstract-declarator of a parameter-declaration.
144
Chris Lattner97316c02008-04-10 02:22:51 +0000145 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000146 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000147 if (DefaultArgChecker.Visit(DefaultArg.get()))
148 return;
149
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000150 // Okay: add the default argument to the parameter
151 Param->setDefaultArg(DefaultArg.take());
152}
153
154// MergeCXXFunctionDecl - Merge two declarations of the same C++
155// function, once we already know that they have the same
156// type. Subroutine of MergeFunctionDecl.
157FunctionDecl *
158Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
159 // C++ [dcl.fct.default]p4:
160 //
161 // For non-template functions, default arguments can be added in
162 // later declarations of a function in the same
163 // scope. Declarations in different scopes have completely
164 // distinct sets of default arguments. That is, declarations in
165 // inner scopes do not acquire default arguments from
166 // declarations in outer scopes, and vice versa. In a given
167 // function declaration, all parameters subsequent to a
168 // parameter with a default argument shall have default
169 // arguments supplied in this or previous declarations. A
170 // default argument shall not be redefined by a later
171 // declaration (not even to the same value).
172 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
173 ParmVarDecl *OldParam = Old->getParamDecl(p);
174 ParmVarDecl *NewParam = New->getParamDecl(p);
175
176 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
177 Diag(NewParam->getLocation(),
178 diag::err_param_default_argument_redefinition,
179 NewParam->getDefaultArg()->getSourceRange());
180 Diag(OldParam->getLocation(), diag::err_previous_definition);
181 } else if (OldParam->getDefaultArg()) {
182 // Merge the old default argument into the new parameter
183 NewParam->setDefaultArg(OldParam->getDefaultArg());
184 }
185 }
186
187 return New;
188}
189
190/// CheckCXXDefaultArguments - Verify that the default arguments for a
191/// function declaration are well-formed according to C++
192/// [dcl.fct.default].
193void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
194 unsigned NumParams = FD->getNumParams();
195 unsigned p;
196
197 // Find first parameter with a default argument
198 for (p = 0; p < NumParams; ++p) {
199 ParmVarDecl *Param = FD->getParamDecl(p);
200 if (Param->getDefaultArg())
201 break;
202 }
203
204 // C++ [dcl.fct.default]p4:
205 // In a given function declaration, all parameters
206 // subsequent to a parameter with a default argument shall
207 // have default arguments supplied in this or previous
208 // declarations. A default argument shall not be redefined
209 // by a later declaration (not even to the same value).
210 unsigned LastMissingDefaultArg = 0;
211 for(; p < NumParams; ++p) {
212 ParmVarDecl *Param = FD->getParamDecl(p);
213 if (!Param->getDefaultArg()) {
214 if (Param->getIdentifier())
215 Diag(Param->getLocation(),
216 diag::err_param_default_argument_missing_name,
217 Param->getIdentifier()->getName());
218 else
219 Diag(Param->getLocation(),
220 diag::err_param_default_argument_missing);
221
222 LastMissingDefaultArg = p;
223 }
224 }
225
226 if (LastMissingDefaultArg > 0) {
227 // Some default arguments were missing. Clear out all of the
228 // default arguments up to (and including) the last missing
229 // default argument, so that we leave the function parameters
230 // in a semantically valid state.
231 for (p = 0; p <= LastMissingDefaultArg; ++p) {
232 ParmVarDecl *Param = FD->getParamDecl(p);
233 if (Param->getDefaultArg()) {
234 delete Param->getDefaultArg();
235 Param->setDefaultArg(0);
236 }
237 }
238 }
239}
Douglas Gregorec93f442008-04-13 21:30:24 +0000240
241/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
242/// one entry in the base class list of a class specifier, for
243/// example:
244/// class foo : public bar, virtual private baz {
245/// 'public bar' and 'virtual private baz' are each base-specifiers.
246void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
247 bool Virtual, AccessSpecifier Access,
248 DeclTy *basetype, SourceLocation BaseLoc) {
249 RecordDecl *Decl = (RecordDecl*)classdecl;
250 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
251
252 // Base specifiers must be record types.
253 if (!BaseType->isRecordType()) {
254 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
255 return;
256 }
257
258 // C++ [class.union]p1:
259 // A union shall not be used as a base class.
260 if (BaseType->isUnionType()) {
261 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
262 return;
263 }
264
265 // C++ [class.union]p1:
266 // A union shall not have base classes.
267 if (Decl->getKind() == Decl::Union) {
268 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
269 SpecifierRange);
270 Decl->setInvalidDecl();
271 return;
272 }
273
274 // C++ [class.derived]p2:
275 // The class-name in a base-specifier shall not be an incompletely
276 // defined class.
277 if (BaseType->isIncompleteType()) {
278 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
279 return;
280 }
281
282 // FIXME: C++ [class.mi]p3:
283 // A class shall not be specified as a direct base class of a
284 // derived class more than once.
285
286 // FIXME: Attach base class to the record.
287}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000288
289
290//===----------------------------------------------------------------------===//
291// Namespace Handling
292//===----------------------------------------------------------------------===//
293
294/// ActOnStartNamespaceDef - This is called at the start of a namespace
295/// definition.
296Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
297 SourceLocation IdentLoc,
298 IdentifierInfo *II,
299 SourceLocation LBrace) {
300 NamespaceDecl *Namespc =
301 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
302 Namespc->setLBracLoc(LBrace);
303
304 Scope *DeclRegionScope = NamespcScope->getParent();
305
306 if (II) {
307 // C++ [namespace.def]p2:
308 // The identifier in an original-namespace-definition shall not have been
309 // previously defined in the declarative region in which the
310 // original-namespace-definition appears. The identifier in an
311 // original-namespace-definition is the name of the namespace. Subsequently
312 // in that declarative region, it is treated as an original-namespace-name.
313
314 Decl *PrevDecl =
315 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
316 /*enableLazyBuiltinCreation=*/false);
317
318 if (PrevDecl && DeclRegionScope->isDeclScope(PrevDecl)) {
319 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
320 // This is an extended namespace definition.
321 // Attach this namespace decl to the chain of extended namespace
322 // definitions.
323 NamespaceDecl *NextNS = OrigNS;
324 while (NextNS->getNextNamespace())
325 NextNS = NextNS->getNextNamespace();
326
327 NextNS->setNextNamespace(Namespc);
328 Namespc->setOriginalNamespace(OrigNS);
329
330 // We won't add this decl to the current scope. We want the namespace
331 // name to return the original namespace decl during a name lookup.
332 } else {
333 // This is an invalid name redefinition.
334 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
335 Namespc->getName());
336 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
337 Namespc->setInvalidDecl();
338 // Continue on to push Namespc as current DeclContext and return it.
339 }
340 } else {
341 // This namespace name is declared for the first time.
342 PushOnScopeChains(Namespc, DeclRegionScope);
343 }
344 }
345 else {
346 // FIXME: Handle anonymous namespaces
347 }
348
349 // Although we could have an invalid decl (i.e. the namespace name is a
350 // redefinition), push it as current DeclContext and try to continue parsing.
351 PushDeclContext(Namespc->getOriginalNamespace());
352 return Namespc;
353}
354
355/// ActOnFinishNamespaceDef - This callback is called after a namespace is
356/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
357void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
358 Decl *Dcl = static_cast<Decl *>(D);
359 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
360 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
361 Namespc->setRBracLoc(RBrace);
362 PopDeclContext();
363}