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