SemaDeclCXX.cpp revision 6d6eb57225b53fb627c565861d1d0e90645400d1
1//===------ 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"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/Type.h"
20#include "clang/Parse/Scope.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/Support/Compiler.h"
23
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// CheckDefaultArgumentVisitor
28//===----------------------------------------------------------------------===//
29
30namespace {
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;
41
42  public:
43    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
44      : DefaultArg(defarg), S(s) {}
45
46    bool VisitExpr(Expr *Node);
47    bool VisitDeclRefExpr(DeclRefExpr *DRE);
48  };
49
50  /// 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);
57
58    return IsInvalid;
59  }
60
61  /// 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());
78    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
79      // C++ [dcl.fct.default]p7
80      //   Local variables shall not be used in default argument
81      //   expressions.
82      if (VDecl->isBlockVarDecl())
83        return S->Diag(DRE->getSourceRange().getBegin(),
84                       diag::err_param_default_argument_references_local,
85                       VDecl->getName(), DefaultArg->getSourceRange());
86    }
87
88    // FIXME: when Clang has support for member functions, "this"
89    // will also need to be diagnosed.
90
91    return false;
92  }
93}
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.
98void
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  // Check that the default argument is well-formed
138  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
139  if (DefaultArgChecker.Visit(DefaultArg.get()))
140    return;
141
142  // Okay: add the default argument to the parameter
143  Param->setDefaultArg(DefaultArg.take());
144}
145
146/// CheckExtraCXXDefaultArguments - Check for any extra default
147/// arguments in the declarator, which is not a function declaration
148/// or definition and therefore is not permitted to have default
149/// arguments. This routine should be invoked for every declarator
150/// that is not a function declaration or definition.
151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
152  // C++ [dcl.fct.default]p3
153  //   A default argument expression shall be specified only in the
154  //   parameter-declaration-clause of a function declaration or in a
155  //   template-parameter (14.1). It shall not be specified for a
156  //   parameter pack. If it is specified in a
157  //   parameter-declaration-clause, it shall not occur within a
158  //   declarator or abstract-declarator of a parameter-declaration.
159  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
160    DeclaratorChunk &chunk = D.getTypeObject(i);
161    if (chunk.Kind == DeclaratorChunk::Function) {
162      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
163        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
164        if (Param->getDefaultArg()) {
165          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
166               Param->getDefaultArg()->getSourceRange());
167          Param->setDefaultArg(0);
168        }
169      }
170    }
171  }
172}
173
174// MergeCXXFunctionDecl - Merge two declarations of the same C++
175// function, once we already know that they have the same
176// type. Subroutine of MergeFunctionDecl.
177FunctionDecl *
178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
179  // C++ [dcl.fct.default]p4:
180  //
181  //   For non-template functions, default arguments can be added in
182  //   later declarations of a function in the same
183  //   scope. Declarations in different scopes have completely
184  //   distinct sets of default arguments. That is, declarations in
185  //   inner scopes do not acquire default arguments from
186  //   declarations in outer scopes, and vice versa. In a given
187  //   function declaration, all parameters subsequent to a
188  //   parameter with a default argument shall have default
189  //   arguments supplied in this or previous declarations. A
190  //   default argument shall not be redefined by a later
191  //   declaration (not even to the same value).
192  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
193    ParmVarDecl *OldParam = Old->getParamDecl(p);
194    ParmVarDecl *NewParam = New->getParamDecl(p);
195
196    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
197      Diag(NewParam->getLocation(),
198           diag::err_param_default_argument_redefinition,
199           NewParam->getDefaultArg()->getSourceRange());
200      Diag(OldParam->getLocation(), diag::err_previous_definition);
201    } else if (OldParam->getDefaultArg()) {
202      // Merge the old default argument into the new parameter
203      NewParam->setDefaultArg(OldParam->getDefaultArg());
204    }
205  }
206
207  return New;
208}
209
210/// CheckCXXDefaultArguments - Verify that the default arguments for a
211/// function declaration are well-formed according to C++
212/// [dcl.fct.default].
213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
214  unsigned NumParams = FD->getNumParams();
215  unsigned p;
216
217  // Find first parameter with a default argument
218  for (p = 0; p < NumParams; ++p) {
219    ParmVarDecl *Param = FD->getParamDecl(p);
220    if (Param->getDefaultArg())
221      break;
222  }
223
224  // C++ [dcl.fct.default]p4:
225  //   In a given function declaration, all parameters
226  //   subsequent to a parameter with a default argument shall
227  //   have default arguments supplied in this or previous
228  //   declarations. A default argument shall not be redefined
229  //   by a later declaration (not even to the same value).
230  unsigned LastMissingDefaultArg = 0;
231  for(; p < NumParams; ++p) {
232    ParmVarDecl *Param = FD->getParamDecl(p);
233    if (!Param->getDefaultArg()) {
234      if (Param->getIdentifier())
235        Diag(Param->getLocation(),
236             diag::err_param_default_argument_missing_name,
237             Param->getIdentifier()->getName());
238      else
239        Diag(Param->getLocation(),
240             diag::err_param_default_argument_missing);
241
242      LastMissingDefaultArg = p;
243    }
244  }
245
246  if (LastMissingDefaultArg > 0) {
247    // Some default arguments were missing. Clear out all of the
248    // default arguments up to (and including) the last missing
249    // default argument, so that we leave the function parameters
250    // in a semantically valid state.
251    for (p = 0; p <= LastMissingDefaultArg; ++p) {
252      ParmVarDecl *Param = FD->getParamDecl(p);
253      if (Param->getDefaultArg()) {
254        delete Param->getDefaultArg();
255        Param->setDefaultArg(0);
256      }
257    }
258  }
259}
260
261/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
262/// one entry in the base class list of a class specifier, for
263/// example:
264///    class foo : public bar, virtual private baz {
265/// 'public bar' and 'virtual private baz' are each base-specifiers.
266void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
267                              bool Virtual, AccessSpecifier Access,
268                              DeclTy *basetype, SourceLocation BaseLoc) {
269  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);
275    return;
276  }
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);
282    return;
283  }
284
285  // C++ [class.union]p1:
286  //   A union shall not have base classes.
287  if (Decl->getKind() == Decl::Union) {
288    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
289         SpecifierRange);
290    Decl->setInvalidDecl();
291    return;
292  }
293
294  // C++ [class.derived]p2:
295  //   The class-name in a base-specifier shall not be an incompletely
296  //   defined class.
297  if (BaseType->isIncompleteType()) {
298    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
299    return;
300  }
301
302  // FIXME: C++ [class.mi]p3:
303  //   A class shall not be specified as a direct base class of a
304  //   derived class more than once.
305
306  // FIXME: Attach base class to the record.
307}
308
309
310//===----------------------------------------------------------------------===//
311// Namespace Handling
312//===----------------------------------------------------------------------===//
313
314/// ActOnStartNamespaceDef - This is called at the start of a namespace
315/// definition.
316Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
317                                           SourceLocation IdentLoc,
318                                           IdentifierInfo *II,
319                                           SourceLocation LBrace) {
320  NamespaceDecl *Namespc =
321      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
322  Namespc->setLBracLoc(LBrace);
323
324  Scope *DeclRegionScope = NamespcScope->getParent();
325
326  if (II) {
327    // C++ [namespace.def]p2:
328    // The identifier in an original-namespace-definition shall not have been
329    // previously defined in the declarative region in which the
330    // original-namespace-definition appears. The identifier in an
331    // original-namespace-definition is the name of the namespace. Subsequently
332    // in that declarative region, it is treated as an original-namespace-name.
333
334    Decl *PrevDecl =
335        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
336                   /*enableLazyBuiltinCreation=*/false);
337
338    if (PrevDecl && DeclRegionScope->isDeclScope(PrevDecl)) {
339      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
340        // This is an extended namespace definition.
341        // Attach this namespace decl to the chain of extended namespace
342        // definitions.
343        NamespaceDecl *NextNS = OrigNS;
344        while (NextNS->getNextNamespace())
345          NextNS = NextNS->getNextNamespace();
346
347        NextNS->setNextNamespace(Namespc);
348        Namespc->setOriginalNamespace(OrigNS);
349
350        // We won't add this decl to the current scope. We want the namespace
351        // name to return the original namespace decl during a name lookup.
352      } else {
353        // This is an invalid name redefinition.
354        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
355          Namespc->getName());
356        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
357        Namespc->setInvalidDecl();
358        // Continue on to push Namespc as current DeclContext and return it.
359      }
360    } else {
361      // This namespace name is declared for the first time.
362      PushOnScopeChains(Namespc, DeclRegionScope);
363    }
364  }
365  else {
366    // FIXME: Handle anonymous namespaces
367  }
368
369  // Although we could have an invalid decl (i.e. the namespace name is a
370  // redefinition), push it as current DeclContext and try to continue parsing.
371  PushDeclContext(Namespc->getOriginalNamespace());
372  return Namespc;
373}
374
375/// ActOnFinishNamespaceDef - This callback is called after a namespace is
376/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
377void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
378  Decl *Dcl = static_cast<Decl *>(D);
379  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
380  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
381  Namespc->setRBracLoc(RBrace);
382  PopDeclContext();
383}
384