SemaDeclCXX.cpp revision 12bc692a78582f1cc32791325981aadcffb04c5e
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/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/Support/Compiler.h"
28
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
35namespace {
36  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
37  /// the default argument of a parameter to determine whether it
38  /// contains any ill-formed subexpressions. For example, this will
39  /// diagnose the use of local variables or parameters within the
40  /// default argument expression.
41  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
42    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
43    Expr *DefaultArg;
44    Sema *S;
45
46  public:
47    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
48      : DefaultArg(defarg), S(s) {}
49
50    bool VisitExpr(Expr *Node);
51    bool VisitDeclRefExpr(DeclRefExpr *DRE);
52  };
53
54  /// VisitExpr - Visit all of the children of this expression.
55  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56    bool IsInvalid = false;
57    for (Stmt::child_iterator I = Node->child_begin(),
58         E = Node->child_end(); I != E; ++I)
59      IsInvalid |= Visit(*I);
60    return IsInvalid;
61  }
62
63  /// VisitDeclRefExpr - Visit a reference to a declaration, to
64  /// determine whether this declaration can be used in the default
65  /// argument expression.
66  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
67    ValueDecl *Decl = DRE->getDecl();
68    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69      // C++ [dcl.fct.default]p9
70      //   Default arguments are evaluated each time the function is
71      //   called. The order of evaluation of function arguments is
72      //   unspecified. Consequently, parameters of a function shall not
73      //   be used in default argument expressions, even if they are not
74      //   evaluated. Parameters of a function declared before a default
75      //   argument expression are in scope and can hide namespace and
76      //   class member names.
77      return S->Diag(DRE->getSourceRange().getBegin(),
78                     diag::err_param_default_argument_references_param,
79                     Param->getName(), DefaultArg->getSourceRange());
80    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
81      // C++ [dcl.fct.default]p7
82      //   Local variables shall not be used in default argument
83      //   expressions.
84      if (VDecl->isBlockVarDecl())
85        return S->Diag(DRE->getSourceRange().getBegin(),
86                       diag::err_param_default_argument_references_local,
87                       VDecl->getName(), DefaultArg->getSourceRange());
88    }
89
90    // FIXME: when Clang has support for member functions, "this"
91    // will also need to be diagnosed.
92
93    return false;
94  }
95}
96
97/// ActOnParamDefaultArgument - Check whether the default argument
98/// provided for a function parameter is well-formed. If so, attach it
99/// to the parameter declaration.
100void
101Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
102                                ExprTy *defarg) {
103  ParmVarDecl *Param = (ParmVarDecl *)param;
104  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
105  QualType ParamType = Param->getType();
106
107  // Default arguments are only permitted in C++
108  if (!getLangOptions().CPlusPlus) {
109    Diag(EqualLoc, diag::err_param_default_argument,
110         DefaultArg->getSourceRange());
111    return;
112  }
113
114  // C++ [dcl.fct.default]p5
115  //   A default argument expression is implicitly converted (clause
116  //   4) to the parameter type. The default argument expression has
117  //   the same semantic constraints as the initializer expression in
118  //   a declaration of a variable of the parameter type, using the
119  //   copy-initialization semantics (8.5).
120  //
121  // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
122  // for C++ (since we want copy-initialization, not copy-assignment),
123  // but we don't have the right semantics implemented yet. Because of
124  // this, our error message is also very poor.
125  QualType DefaultArgType = DefaultArg->getType();
126  Expr *DefaultArgPtr = DefaultArg.get();
127  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
128                                                              DefaultArgPtr);
129  if (DefaultArgPtr != DefaultArg.get()) {
130    DefaultArg.take();
131    DefaultArg.reset(DefaultArgPtr);
132  }
133  if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
134                               ParamType, DefaultArgType, DefaultArg.get(),
135                               "in default argument")) {
136    return;
137  }
138
139  // Check that the default argument is well-formed
140  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
141  if (DefaultArgChecker.Visit(DefaultArg.get()))
142    return;
143
144  // Okay: add the default argument to the parameter
145  Param->setDefaultArg(DefaultArg.take());
146}
147
148/// CheckExtraCXXDefaultArguments - Check for any extra default
149/// arguments in the declarator, which is not a function declaration
150/// or definition and therefore is not permitted to have default
151/// arguments. This routine should be invoked for every declarator
152/// that is not a function declaration or definition.
153void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
154  // C++ [dcl.fct.default]p3
155  //   A default argument expression shall be specified only in the
156  //   parameter-declaration-clause of a function declaration or in a
157  //   template-parameter (14.1). It shall not be specified for a
158  //   parameter pack. If it is specified in a
159  //   parameter-declaration-clause, it shall not occur within a
160  //   declarator or abstract-declarator of a parameter-declaration.
161  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
162    DeclaratorChunk &chunk = D.getTypeObject(i);
163    if (chunk.Kind == DeclaratorChunk::Function) {
164      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
165        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
166        if (Param->getDefaultArg()) {
167          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
168               Param->getDefaultArg()->getSourceRange());
169          Param->setDefaultArg(0);
170        }
171      }
172    }
173  }
174}
175
176// MergeCXXFunctionDecl - Merge two declarations of the same C++
177// function, once we already know that they have the same
178// type. Subroutine of MergeFunctionDecl.
179FunctionDecl *
180Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
181  // C++ [dcl.fct.default]p4:
182  //
183  //   For non-template functions, default arguments can be added in
184  //   later declarations of a function in the same
185  //   scope. Declarations in different scopes have completely
186  //   distinct sets of default arguments. That is, declarations in
187  //   inner scopes do not acquire default arguments from
188  //   declarations in outer scopes, and vice versa. In a given
189  //   function declaration, all parameters subsequent to a
190  //   parameter with a default argument shall have default
191  //   arguments supplied in this or previous declarations. A
192  //   default argument shall not be redefined by a later
193  //   declaration (not even to the same value).
194  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
195    ParmVarDecl *OldParam = Old->getParamDecl(p);
196    ParmVarDecl *NewParam = New->getParamDecl(p);
197
198    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
199      Diag(NewParam->getLocation(),
200           diag::err_param_default_argument_redefinition,
201           NewParam->getDefaultArg()->getSourceRange());
202      Diag(OldParam->getLocation(), diag::err_previous_definition);
203    } else if (OldParam->getDefaultArg()) {
204      // Merge the old default argument into the new parameter
205      NewParam->setDefaultArg(OldParam->getDefaultArg());
206    }
207  }
208
209  return New;
210}
211
212/// CheckCXXDefaultArguments - Verify that the default arguments for a
213/// function declaration are well-formed according to C++
214/// [dcl.fct.default].
215void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
216  unsigned NumParams = FD->getNumParams();
217  unsigned p;
218
219  // Find first parameter with a default argument
220  for (p = 0; p < NumParams; ++p) {
221    ParmVarDecl *Param = FD->getParamDecl(p);
222    if (Param->getDefaultArg())
223      break;
224  }
225
226  // C++ [dcl.fct.default]p4:
227  //   In a given function declaration, all parameters
228  //   subsequent to a parameter with a default argument shall
229  //   have default arguments supplied in this or previous
230  //   declarations. A default argument shall not be redefined
231  //   by a later declaration (not even to the same value).
232  unsigned LastMissingDefaultArg = 0;
233  for(; p < NumParams; ++p) {
234    ParmVarDecl *Param = FD->getParamDecl(p);
235    if (!Param->getDefaultArg()) {
236      if (Param->getIdentifier())
237        Diag(Param->getLocation(),
238             diag::err_param_default_argument_missing_name,
239             Param->getIdentifier()->getName());
240      else
241        Diag(Param->getLocation(),
242             diag::err_param_default_argument_missing);
243
244      LastMissingDefaultArg = p;
245    }
246  }
247
248  if (LastMissingDefaultArg > 0) {
249    // Some default arguments were missing. Clear out all of the
250    // default arguments up to (and including) the last missing
251    // default argument, so that we leave the function parameters
252    // in a semantically valid state.
253    for (p = 0; p <= LastMissingDefaultArg; ++p) {
254      ParmVarDecl *Param = FD->getParamDecl(p);
255      if (Param->getDefaultArg()) {
256        delete Param->getDefaultArg();
257        Param->setDefaultArg(0);
258      }
259    }
260  }
261}
262
263/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
264/// one entry in the base class list of a class specifier, for
265/// example:
266///    class foo : public bar, virtual private baz {
267/// 'public bar' and 'virtual private baz' are each base-specifiers.
268void Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
269                              bool Virtual, AccessSpecifier Access,
270                              TypeTy *basetype, SourceLocation BaseLoc) {
271  RecordDecl *Decl = (RecordDecl*)classdecl;
272  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
273
274  // Base specifiers must be record types.
275  if (!BaseType->isRecordType()) {
276    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
277    return;
278  }
279
280  // C++ [class.union]p1:
281  //   A union shall not be used as a base class.
282  if (BaseType->isUnionType()) {
283    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
284    return;
285  }
286
287  // C++ [class.union]p1:
288  //   A union shall not have base classes.
289  if (Decl->isUnion()) {
290    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
291         SpecifierRange);
292    Decl->setInvalidDecl();
293    return;
294  }
295
296  // C++ [class.derived]p2:
297  //   The class-name in a base-specifier shall not be an incompletely
298  //   defined class.
299  if (BaseType->isIncompleteType()) {
300    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
301    return;
302  }
303
304  // FIXME: C++ [class.mi]p3:
305  //   A class shall not be specified as a direct base class of a
306  //   derived class more than once.
307
308  // FIXME: Attach base class to the record.
309}
310
311//===----------------------------------------------------------------------===//
312// C++ class member Handling
313//===----------------------------------------------------------------------===//
314
315/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
316/// definition, when on C++.
317void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
318  Decl *Dcl = static_cast<Decl *>(D);
319  PushDeclContext(cast<CXXRecordDecl>(Dcl));
320  FieldCollector->StartClass();
321}
322
323/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
324/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
325/// bitfield width if there is one and 'InitExpr' specifies the initializer if
326/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
327/// declarators on it.
328///
329/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
330/// an instance field is declared, a new CXXFieldDecl is created but the method
331/// does *not* return it; it returns LastInGroup instead. The other C++ members
332/// (which are all ScopedDecls) are returned after appending them to
333/// LastInGroup.
334Sema::DeclTy *
335Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
336                               ExprTy *BW, ExprTy *InitExpr,
337                               DeclTy *LastInGroup) {
338  const DeclSpec &DS = D.getDeclSpec();
339  IdentifierInfo *II = D.getIdentifier();
340  Expr *BitWidth = static_cast<Expr*>(BW);
341  Expr *Init = static_cast<Expr*>(InitExpr);
342  SourceLocation Loc = D.getIdentifierLoc();
343
344  // C++ 9.2p6: A member shall not be declared to have automatic storage
345  // duration (auto, register) or with the extern storage-class-specifier.
346  switch (DS.getStorageClassSpec()) {
347    case DeclSpec::SCS_unspecified:
348    case DeclSpec::SCS_typedef:
349    case DeclSpec::SCS_static:
350      // FALL THROUGH.
351      break;
352    default:
353      if (DS.getStorageClassSpecLoc().isValid())
354        Diag(DS.getStorageClassSpecLoc(),
355             diag::err_storageclass_invalid_for_member);
356      else
357        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
358      D.getMutableDeclSpec().ClearStorageClassSpecs();
359  }
360
361  QualType T = GetTypeForDeclarator(D, S);
362
363  // T->isFunctionType() is used instead of D.isFunctionDeclarator() to cover
364  // this case:
365  //
366  // typedef int f();
367  // f a;
368  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
369                      !T->isFunctionType());
370
371  Decl *Member;
372  bool InvalidDecl = false;
373
374  if (isInstField)
375    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
376  else
377    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
378
379  if (!Member) return LastInGroup;
380
381  assert(II || isInstField && "No identifier for non-field ?");
382
383  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
384  // specific methods. Use a wrapper class that can be used with all C++ class
385  // member decls.
386  CXXClassMemberWrapper(Member).setAccess(AS);
387
388  if (BitWidth) {
389    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
390    // constant-expression be a value equal to zero.
391    // FIXME: Check this.
392
393    if (D.isFunctionDeclarator()) {
394      // FIXME: Emit diagnostic about only constructors taking base initializers
395      // or something similar, when constructor support is in place.
396      Diag(Loc, diag::err_not_bitfield_type,
397           II->getName(), BitWidth->getSourceRange());
398      InvalidDecl = true;
399
400    } else if (isInstField || isa<FunctionDecl>(Member)) {
401      // An instance field or a function typedef ("typedef int f(); f a;").
402      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
403      if (!T->isIntegralType()) {
404        Diag(Loc, diag::err_not_integral_type_bitfield,
405             II->getName(), BitWidth->getSourceRange());
406        InvalidDecl = true;
407      }
408
409    } else if (isa<TypedefDecl>(Member)) {
410      // "cannot declare 'A' to be a bit-field type"
411      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
412           BitWidth->getSourceRange());
413      InvalidDecl = true;
414
415    } else {
416      assert(isa<CXXClassVarDecl>(Member) &&
417             "Didn't we cover all member kinds?");
418      // C++ 9.6p3: A bit-field shall not be a static member.
419      // "static member 'A' cannot be a bit-field"
420      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
421           BitWidth->getSourceRange());
422      InvalidDecl = true;
423    }
424  }
425
426  if (Init) {
427    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
428    // if it declares a static member of const integral or const enumeration
429    // type.
430    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
431      // ...static member of...
432      CVD->setInit(Init);
433      // ...const integral or const enumeration type.
434      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
435          CVD->getType()->isIntegralType()) {
436        // constant-initializer
437        if (CheckForConstantInitializer(Init, CVD->getType()))
438          InvalidDecl = true;
439
440      } else {
441        // not const integral.
442        Diag(Loc, diag::err_member_initialization,
443             II->getName(), Init->getSourceRange());
444        InvalidDecl = true;
445      }
446
447    } else {
448      // not static member.
449      Diag(Loc, diag::err_member_initialization,
450           II->getName(), Init->getSourceRange());
451      InvalidDecl = true;
452    }
453  }
454
455  if (InvalidDecl)
456    Member->setInvalidDecl();
457
458  if (isInstField) {
459    FieldCollector->Add(cast<CXXFieldDecl>(Member));
460    return LastInGroup;
461  }
462  return Member;
463}
464
465void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
466                                             DeclTy *TagDecl,
467                                             SourceLocation LBrac,
468                                             SourceLocation RBrac) {
469  ActOnFields(S, RLoc, TagDecl,
470              (DeclTy**)FieldCollector->getCurFields(),
471              FieldCollector->getCurNumFields(), LBrac, RBrac);
472}
473
474void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
475  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
476  FieldCollector->FinishClass();
477  PopDeclContext();
478
479  // Everything, including inline method definitions, have been parsed.
480  // Let the consumer know of the new TagDecl definition.
481  Consumer.HandleTagDeclDefinition(Rec);
482}
483
484//===----------------------------------------------------------------------===//
485// Namespace Handling
486//===----------------------------------------------------------------------===//
487
488/// ActOnStartNamespaceDef - This is called at the start of a namespace
489/// definition.
490Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
491                                           SourceLocation IdentLoc,
492                                           IdentifierInfo *II,
493                                           SourceLocation LBrace) {
494  NamespaceDecl *Namespc =
495      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
496  Namespc->setLBracLoc(LBrace);
497
498  Scope *DeclRegionScope = NamespcScope->getParent();
499
500  if (II) {
501    // C++ [namespace.def]p2:
502    // The identifier in an original-namespace-definition shall not have been
503    // previously defined in the declarative region in which the
504    // original-namespace-definition appears. The identifier in an
505    // original-namespace-definition is the name of the namespace. Subsequently
506    // in that declarative region, it is treated as an original-namespace-name.
507
508    Decl *PrevDecl =
509        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
510                   /*enableLazyBuiltinCreation=*/false);
511
512    if (PrevDecl &&
513        IdResolver.isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
514      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
515        // This is an extended namespace definition.
516        // Attach this namespace decl to the chain of extended namespace
517        // definitions.
518        NamespaceDecl *NextNS = OrigNS;
519        while (NextNS->getNextNamespace())
520          NextNS = NextNS->getNextNamespace();
521
522        NextNS->setNextNamespace(Namespc);
523        Namespc->setOriginalNamespace(OrigNS);
524
525        // We won't add this decl to the current scope. We want the namespace
526        // name to return the original namespace decl during a name lookup.
527      } else {
528        // This is an invalid name redefinition.
529        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
530          Namespc->getName());
531        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
532        Namespc->setInvalidDecl();
533        // Continue on to push Namespc as current DeclContext and return it.
534      }
535    } else {
536      // This namespace name is declared for the first time.
537      PushOnScopeChains(Namespc, DeclRegionScope);
538    }
539  }
540  else {
541    // FIXME: Handle anonymous namespaces
542  }
543
544  // Although we could have an invalid decl (i.e. the namespace name is a
545  // redefinition), push it as current DeclContext and try to continue parsing.
546  PushDeclContext(Namespc->getOriginalNamespace());
547  return Namespc;
548}
549
550/// ActOnFinishNamespaceDef - This callback is called after a namespace is
551/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
552void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
553  Decl *Dcl = static_cast<Decl *>(D);
554  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
555  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
556  Namespc->setRBracLoc(RBrace);
557  PopDeclContext();
558}
559