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