SemaDeclCXX.cpp revision 31fc07df7f0fc89ebf83ca05a20b29de45a7598d
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/TypeOrdering.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/Support/Compiler.h"
23#include <algorithm> // for std::equal
24#include <map>
25
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
32namespace {
33  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34  /// the default argument of a parameter to determine whether it
35  /// contains any ill-formed subexpressions. For example, this will
36  /// diagnose the use of local variables or parameters within the
37  /// default argument expression.
38  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
39    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
40    Expr *DefaultArg;
41    Sema *S;
42
43  public:
44    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45      : DefaultArg(defarg), S(s) {}
46
47    bool VisitExpr(Expr *Node);
48    bool VisitDeclRefExpr(DeclRefExpr *DRE);
49  };
50
51  /// VisitExpr - Visit all of the children of this expression.
52  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
53    bool IsInvalid = false;
54    for (Stmt::child_iterator I = Node->child_begin(),
55         E = Node->child_end(); I != E; ++I)
56      IsInvalid |= Visit(*I);
57    return IsInvalid;
58  }
59
60  /// VisitDeclRefExpr - Visit a reference to a declaration, to
61  /// determine whether this declaration can be used in the default
62  /// argument expression.
63  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
64    NamedDecl *Decl = DRE->getDecl();
65    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
66      // C++ [dcl.fct.default]p9
67      //   Default arguments are evaluated each time the function is
68      //   called. The order of evaluation of function arguments is
69      //   unspecified. Consequently, parameters of a function shall not
70      //   be used in default argument expressions, even if they are not
71      //   evaluated. Parameters of a function declared before a default
72      //   argument expression are in scope and can hide namespace and
73      //   class member names.
74      return S->Diag(DRE->getSourceRange().getBegin(),
75                     diag::err_param_default_argument_references_param,
76                     Param->getName(), DefaultArg->getSourceRange());
77    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
78      // C++ [dcl.fct.default]p7
79      //   Local variables shall not be used in default argument
80      //   expressions.
81      if (VDecl->isBlockVarDecl())
82        return S->Diag(DRE->getSourceRange().getBegin(),
83                       diag::err_param_default_argument_references_local,
84                       VDecl->getName(), DefaultArg->getSourceRange());
85    }
86
87    // FIXME: when Clang has support for member functions, "this"
88    // will also need to be diagnosed.
89
90    return false;
91  }
92}
93
94/// ActOnParamDefaultArgument - Check whether the default argument
95/// provided for a function parameter is well-formed. If so, attach it
96/// to the parameter declaration.
97void
98Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
99                                ExprTy *defarg) {
100  ParmVarDecl *Param = (ParmVarDecl *)param;
101  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
102  QualType ParamType = Param->getType();
103
104  // Default arguments are only permitted in C++
105  if (!getLangOptions().CPlusPlus) {
106    Diag(EqualLoc, diag::err_param_default_argument,
107         DefaultArg->getSourceRange());
108    return;
109  }
110
111  // C++ [dcl.fct.default]p5
112  //   A default argument expression is implicitly converted (clause
113  //   4) to the parameter type. The default argument expression has
114  //   the same semantic constraints as the initializer expression in
115  //   a declaration of a variable of the parameter type, using the
116  //   copy-initialization semantics (8.5).
117  //
118  // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
119  // for C++ (since we want copy-initialization, not copy-assignment),
120  // but we don't have the right semantics implemented yet. Because of
121  // this, our error message is also very poor.
122  QualType DefaultArgType = DefaultArg->getType();
123  Expr *DefaultArgPtr = DefaultArg.get();
124  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
125                                                              DefaultArgPtr);
126  if (DefaultArgPtr != DefaultArg.get()) {
127    DefaultArg.take();
128    DefaultArg.reset(DefaultArgPtr);
129  }
130  if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
131                               ParamType, DefaultArgType, DefaultArg.get(),
132                               "in default argument")) {
133    return;
134  }
135
136  // Check that the default argument is well-formed
137  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
138  if (DefaultArgChecker.Visit(DefaultArg.get()))
139    return;
140
141  // Okay: add the default argument to the parameter
142  Param->setDefaultArg(DefaultArg.take());
143}
144
145/// CheckExtraCXXDefaultArguments - Check for any extra default
146/// arguments in the declarator, which is not a function declaration
147/// or definition and therefore is not permitted to have default
148/// arguments. This routine should be invoked for every declarator
149/// that is not a function declaration or definition.
150void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
151  // C++ [dcl.fct.default]p3
152  //   A default argument expression shall be specified only in the
153  //   parameter-declaration-clause of a function declaration or in a
154  //   template-parameter (14.1). It shall not be specified for a
155  //   parameter pack. If it is specified in a
156  //   parameter-declaration-clause, it shall not occur within a
157  //   declarator or abstract-declarator of a parameter-declaration.
158  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
159    DeclaratorChunk &chunk = D.getTypeObject(i);
160    if (chunk.Kind == DeclaratorChunk::Function) {
161      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
162        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
163        if (Param->getDefaultArg()) {
164          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
165               Param->getDefaultArg()->getSourceRange());
166          Param->setDefaultArg(0);
167        }
168      }
169    }
170  }
171}
172
173// MergeCXXFunctionDecl - Merge two declarations of the same C++
174// function, once we already know that they have the same
175// type. Subroutine of MergeFunctionDecl.
176FunctionDecl *
177Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
178  // C++ [dcl.fct.default]p4:
179  //
180  //   For non-template functions, default arguments can be added in
181  //   later declarations of a function in the same
182  //   scope. Declarations in different scopes have completely
183  //   distinct sets of default arguments. That is, declarations in
184  //   inner scopes do not acquire default arguments from
185  //   declarations in outer scopes, and vice versa. In a given
186  //   function declaration, all parameters subsequent to a
187  //   parameter with a default argument shall have default
188  //   arguments supplied in this or previous declarations. A
189  //   default argument shall not be redefined by a later
190  //   declaration (not even to the same value).
191  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
192    ParmVarDecl *OldParam = Old->getParamDecl(p);
193    ParmVarDecl *NewParam = New->getParamDecl(p);
194
195    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
196      Diag(NewParam->getLocation(),
197           diag::err_param_default_argument_redefinition,
198           NewParam->getDefaultArg()->getSourceRange());
199      Diag(OldParam->getLocation(), diag::err_previous_definition);
200    } else if (OldParam->getDefaultArg()) {
201      // Merge the old default argument into the new parameter
202      NewParam->setDefaultArg(OldParam->getDefaultArg());
203    }
204  }
205
206  return New;
207}
208
209/// CheckCXXDefaultArguments - Verify that the default arguments for a
210/// function declaration are well-formed according to C++
211/// [dcl.fct.default].
212void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
213  unsigned NumParams = FD->getNumParams();
214  unsigned p;
215
216  // Find first parameter with a default argument
217  for (p = 0; p < NumParams; ++p) {
218    ParmVarDecl *Param = FD->getParamDecl(p);
219    if (Param->getDefaultArg())
220      break;
221  }
222
223  // C++ [dcl.fct.default]p4:
224  //   In a given function declaration, all parameters
225  //   subsequent to a parameter with a default argument shall
226  //   have default arguments supplied in this or previous
227  //   declarations. A default argument shall not be redefined
228  //   by a later declaration (not even to the same value).
229  unsigned LastMissingDefaultArg = 0;
230  for(; p < NumParams; ++p) {
231    ParmVarDecl *Param = FD->getParamDecl(p);
232    if (!Param->getDefaultArg()) {
233      if (Param->getIdentifier())
234        Diag(Param->getLocation(),
235             diag::err_param_default_argument_missing_name,
236             Param->getIdentifier()->getName());
237      else
238        Diag(Param->getLocation(),
239             diag::err_param_default_argument_missing);
240
241      LastMissingDefaultArg = p;
242    }
243  }
244
245  if (LastMissingDefaultArg > 0) {
246    // Some default arguments were missing. Clear out all of the
247    // default arguments up to (and including) the last missing
248    // default argument, so that we leave the function parameters
249    // in a semantically valid state.
250    for (p = 0; p <= LastMissingDefaultArg; ++p) {
251      ParmVarDecl *Param = FD->getParamDecl(p);
252      if (Param->getDefaultArg()) {
253        delete Param->getDefaultArg();
254        Param->setDefaultArg(0);
255      }
256    }
257  }
258}
259
260/// isCurrentClassName - Determine whether the identifier II is the
261/// name of the class type currently being defined. In the case of
262/// nested classes, this will only return true if II is the name of
263/// the innermost class.
264bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
265  if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
266    return &II == CurDecl->getIdentifier();
267  else
268    return false;
269}
270
271/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
272/// one entry in the base class list of a class specifier, for
273/// example:
274///    class foo : public bar, virtual private baz {
275/// 'public bar' and 'virtual private baz' are each base-specifiers.
276Sema::BaseResult
277Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
278                         bool Virtual, AccessSpecifier Access,
279                         TypeTy *basetype, SourceLocation BaseLoc) {
280  RecordDecl *Decl = (RecordDecl*)classdecl;
281  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
282
283  // Base specifiers must be record types.
284  if (!BaseType->isRecordType()) {
285    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
286    return true;
287  }
288
289  // C++ [class.union]p1:
290  //   A union shall not be used as a base class.
291  if (BaseType->isUnionType()) {
292    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
293    return true;
294  }
295
296  // C++ [class.union]p1:
297  //   A union shall not have base classes.
298  if (Decl->isUnion()) {
299    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
300         SpecifierRange);
301    return true;
302  }
303
304  // C++ [class.derived]p2:
305  //   The class-name in a base-specifier shall not be an incompletely
306  //   defined class.
307  if (BaseType->isIncompleteType()) {
308    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
309    return true;
310  }
311
312  // Create the base specifier.
313  return new CXXBaseSpecifier(SpecifierRange, Virtual,
314                              BaseType->isClassType(), Access, BaseType);
315}
316
317/// ActOnBaseSpecifiers - Attach the given base specifiers to the
318/// class, after checking whether there are any duplicate base
319/// classes.
320void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
321                               unsigned NumBases) {
322  if (NumBases == 0)
323    return;
324
325  // Used to keep track of which base types we have already seen, so
326  // that we can properly diagnose redundant direct base types. Note
327  // that the key is always the unqualified canonical type of the base
328  // class.
329  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
330
331  // Copy non-redundant base specifiers into permanent storage.
332  CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
333  unsigned NumGoodBases = 0;
334  for (unsigned idx = 0; idx < NumBases; ++idx) {
335    QualType NewBaseType
336      = Context.getCanonicalType(BaseSpecs[idx]->getType());
337    NewBaseType = NewBaseType.getUnqualifiedType();
338
339    if (KnownBaseTypes[NewBaseType]) {
340      // C++ [class.mi]p3:
341      //   A class shall not be specified as a direct base class of a
342      //   derived class more than once.
343      Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
344           diag::err_duplicate_base_class,
345           KnownBaseTypes[NewBaseType]->getType().getAsString(),
346           BaseSpecs[idx]->getSourceRange());
347
348      // Delete the duplicate base class specifier; we're going to
349      // overwrite its pointer later.
350      delete BaseSpecs[idx];
351    } else {
352      // Okay, add this new base class.
353      KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
354      BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
355    }
356  }
357
358  // Attach the remaining base class specifiers to the derived class.
359  CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
360  Decl->setBases(BaseSpecs, NumGoodBases);
361
362  // Delete the remaining (good) base class specifiers, since their
363  // data has been copied into the CXXRecordDecl.
364  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
365    delete BaseSpecs[idx];
366}
367
368//===----------------------------------------------------------------------===//
369// C++ class member Handling
370//===----------------------------------------------------------------------===//
371
372/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
373/// definition, when on C++.
374void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
375  CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
376  PushDeclContext(Dcl);
377  FieldCollector->StartClass();
378
379  if (Dcl->getIdentifier()) {
380    // C++ [class]p2:
381    //   [...] The class-name is also inserted into the scope of the
382    //   class itself; this is known as the injected-class-name. For
383    //   purposes of access checking, the injected-class-name is treated
384    //   as if it were a public member name.
385    TypedefDecl *InjectedClassName
386      = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
387                            Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
388    PushOnScopeChains(InjectedClassName, S);
389  }
390}
391
392/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
393/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
394/// bitfield width if there is one and 'InitExpr' specifies the initializer if
395/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
396/// declarators on it.
397///
398/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
399/// an instance field is declared, a new CXXFieldDecl is created but the method
400/// does *not* return it; it returns LastInGroup instead. The other C++ members
401/// (which are all ScopedDecls) are returned after appending them to
402/// LastInGroup.
403Sema::DeclTy *
404Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
405                               ExprTy *BW, ExprTy *InitExpr,
406                               DeclTy *LastInGroup) {
407  const DeclSpec &DS = D.getDeclSpec();
408  IdentifierInfo *II = D.getIdentifier();
409  Expr *BitWidth = static_cast<Expr*>(BW);
410  Expr *Init = static_cast<Expr*>(InitExpr);
411  SourceLocation Loc = D.getIdentifierLoc();
412
413  // C++ 9.2p6: A member shall not be declared to have automatic storage
414  // duration (auto, register) or with the extern storage-class-specifier.
415  switch (DS.getStorageClassSpec()) {
416    case DeclSpec::SCS_unspecified:
417    case DeclSpec::SCS_typedef:
418    case DeclSpec::SCS_static:
419      // FALL THROUGH.
420      break;
421    default:
422      if (DS.getStorageClassSpecLoc().isValid())
423        Diag(DS.getStorageClassSpecLoc(),
424             diag::err_storageclass_invalid_for_member);
425      else
426        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
427      D.getMutableDeclSpec().ClearStorageClassSpecs();
428  }
429
430  bool isFunc = D.isFunctionDeclarator();
431  if (!isFunc &&
432      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
433      D.getNumTypeObjects() == 0) {
434    // Check also for this case:
435    //
436    // typedef int f();
437    // f a;
438    //
439    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
440    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
441  }
442
443  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
444                      !isFunc);
445
446  Decl *Member;
447  bool InvalidDecl = false;
448
449  if (isInstField)
450    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
451  else
452    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
453
454  if (!Member) return LastInGroup;
455
456  assert((II || isInstField) && "No identifier for non-field ?");
457
458  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
459  // specific methods. Use a wrapper class that can be used with all C++ class
460  // member decls.
461  CXXClassMemberWrapper(Member).setAccess(AS);
462
463  if (BitWidth) {
464    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
465    // constant-expression be a value equal to zero.
466    // FIXME: Check this.
467
468    if (D.isFunctionDeclarator()) {
469      // FIXME: Emit diagnostic about only constructors taking base initializers
470      // or something similar, when constructor support is in place.
471      Diag(Loc, diag::err_not_bitfield_type,
472           II->getName(), BitWidth->getSourceRange());
473      InvalidDecl = true;
474
475    } else if (isInstField) {
476      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
477      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
478        Diag(Loc, diag::err_not_integral_type_bitfield,
479             II->getName(), BitWidth->getSourceRange());
480        InvalidDecl = true;
481      }
482
483    } else if (isa<FunctionDecl>(Member)) {
484      // A function typedef ("typedef int f(); f a;").
485      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
486      Diag(Loc, diag::err_not_integral_type_bitfield,
487           II->getName(), BitWidth->getSourceRange());
488      InvalidDecl = true;
489
490    } else if (isa<TypedefDecl>(Member)) {
491      // "cannot declare 'A' to be a bit-field type"
492      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
493           BitWidth->getSourceRange());
494      InvalidDecl = true;
495
496    } else {
497      assert(isa<CXXClassVarDecl>(Member) &&
498             "Didn't we cover all member kinds?");
499      // C++ 9.6p3: A bit-field shall not be a static member.
500      // "static member 'A' cannot be a bit-field"
501      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
502           BitWidth->getSourceRange());
503      InvalidDecl = true;
504    }
505  }
506
507  if (Init) {
508    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
509    // if it declares a static member of const integral or const enumeration
510    // type.
511    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
512      // ...static member of...
513      CVD->setInit(Init);
514      // ...const integral or const enumeration type.
515      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
516          CVD->getType()->isIntegralType()) {
517        // constant-initializer
518        if (CheckForConstantInitializer(Init, CVD->getType()))
519          InvalidDecl = true;
520
521      } else {
522        // not const integral.
523        Diag(Loc, diag::err_member_initialization,
524             II->getName(), Init->getSourceRange());
525        InvalidDecl = true;
526      }
527
528    } else {
529      // not static member.
530      Diag(Loc, diag::err_member_initialization,
531           II->getName(), Init->getSourceRange());
532      InvalidDecl = true;
533    }
534  }
535
536  if (InvalidDecl)
537    Member->setInvalidDecl();
538
539  if (isInstField) {
540    FieldCollector->Add(cast<CXXFieldDecl>(Member));
541    return LastInGroup;
542  }
543  return Member;
544}
545
546void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
547                                             DeclTy *TagDecl,
548                                             SourceLocation LBrac,
549                                             SourceLocation RBrac) {
550  ActOnFields(S, RLoc, TagDecl,
551              (DeclTy**)FieldCollector->getCurFields(),
552              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
553}
554
555void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
556  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
557  FieldCollector->FinishClass();
558  PopDeclContext();
559
560  // Everything, including inline method definitions, have been parsed.
561  // Let the consumer know of the new TagDecl definition.
562  Consumer.HandleTagDeclDefinition(Rec);
563}
564
565/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
566/// the declaration of the given C++ constructor ConDecl that was
567/// built from declarator D. This routine is responsible for checking
568/// that the newly-created constructor declaration is well-formed and
569/// for recording it in the C++ class. Example:
570///
571/// @code
572/// class X {
573///   X(); // X::X() will be the ConDecl.
574/// };
575/// @endcode
576Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
577  assert(ConDecl && "Expected to receive a constructor declaration");
578  return (DeclTy *)ConDecl;
579}
580
581//===----------------------------------------------------------------------===//
582// Namespace Handling
583//===----------------------------------------------------------------------===//
584
585/// ActOnStartNamespaceDef - This is called at the start of a namespace
586/// definition.
587Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
588                                           SourceLocation IdentLoc,
589                                           IdentifierInfo *II,
590                                           SourceLocation LBrace) {
591  NamespaceDecl *Namespc =
592      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
593  Namespc->setLBracLoc(LBrace);
594
595  Scope *DeclRegionScope = NamespcScope->getParent();
596
597  if (II) {
598    // C++ [namespace.def]p2:
599    // The identifier in an original-namespace-definition shall not have been
600    // previously defined in the declarative region in which the
601    // original-namespace-definition appears. The identifier in an
602    // original-namespace-definition is the name of the namespace. Subsequently
603    // in that declarative region, it is treated as an original-namespace-name.
604
605    Decl *PrevDecl =
606        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
607                   /*enableLazyBuiltinCreation=*/false);
608
609    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
610      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
611        // This is an extended namespace definition.
612        // Attach this namespace decl to the chain of extended namespace
613        // definitions.
614        NamespaceDecl *NextNS = OrigNS;
615        while (NextNS->getNextNamespace())
616          NextNS = NextNS->getNextNamespace();
617
618        NextNS->setNextNamespace(Namespc);
619        Namespc->setOriginalNamespace(OrigNS);
620
621        // We won't add this decl to the current scope. We want the namespace
622        // name to return the original namespace decl during a name lookup.
623      } else {
624        // This is an invalid name redefinition.
625        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
626          Namespc->getName());
627        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
628        Namespc->setInvalidDecl();
629        // Continue on to push Namespc as current DeclContext and return it.
630      }
631    } else {
632      // This namespace name is declared for the first time.
633      PushOnScopeChains(Namespc, DeclRegionScope);
634    }
635  }
636  else {
637    // FIXME: Handle anonymous namespaces
638  }
639
640  // Although we could have an invalid decl (i.e. the namespace name is a
641  // redefinition), push it as current DeclContext and try to continue parsing.
642  PushDeclContext(Namespc->getOriginalNamespace());
643  return Namespc;
644}
645
646/// ActOnFinishNamespaceDef - This callback is called after a namespace is
647/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
648void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
649  Decl *Dcl = static_cast<Decl *>(D);
650  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
651  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
652  Namespc->setRBracLoc(RBrace);
653  PopDeclContext();
654}
655
656
657/// AddCXXDirectInitializerToDecl - This action is called immediately after
658/// ActOnDeclarator, when a C++ direct initializer is present.
659/// e.g: "int x(1);"
660void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
661                                         ExprTy **ExprTys, unsigned NumExprs,
662                                         SourceLocation *CommaLocs,
663                                         SourceLocation RParenLoc) {
664  assert(NumExprs != 0 && ExprTys && "missing expressions");
665  Decl *RealDecl = static_cast<Decl *>(Dcl);
666
667  // If there is no declaration, there was an error parsing it.  Just ignore
668  // the initializer.
669  if (RealDecl == 0) {
670    for (unsigned i = 0; i != NumExprs; ++i)
671      delete static_cast<Expr *>(ExprTys[i]);
672    return;
673  }
674
675  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
676  if (!VDecl) {
677    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
678    RealDecl->setInvalidDecl();
679    return;
680  }
681
682  // We will treat direct-initialization as a copy-initialization:
683  //    int x(1);  -as-> int x = 1;
684  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
685  //
686  // Clients that want to distinguish between the two forms, can check for
687  // direct initializer using VarDecl::hasCXXDirectInitializer().
688  // A major benefit is that clients that don't particularly care about which
689  // exactly form was it (like the CodeGen) can handle both cases without
690  // special case code.
691
692  // C++ 8.5p11:
693  // The form of initialization (using parentheses or '=') is generally
694  // insignificant, but does matter when the entity being initialized has a
695  // class type.
696
697  if (VDecl->getType()->isRecordType()) {
698    // FIXME: When constructors for class types are supported, determine how
699    // exactly semantic checking will be done for direct initializers.
700    unsigned DiagID = PP.getDiagnostics().getCustomDiagID(Diagnostic::Error,
701                           "initialization for class types is not handled yet");
702    Diag(VDecl->getLocation(), DiagID);
703    RealDecl->setInvalidDecl();
704    return;
705  }
706
707  if (NumExprs > 1) {
708    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
709         SourceRange(VDecl->getLocation(), RParenLoc));
710    RealDecl->setInvalidDecl();
711    return;
712  }
713
714  // Let clients know that initialization was done with a direct initializer.
715  VDecl->setCXXDirectInitializer(true);
716
717  assert(NumExprs == 1 && "Expected 1 expression");
718  // Set the init expression, handles conversions.
719  AddInitializerToDecl(Dcl, ExprTys[0]);
720}
721
722/// CompareReferenceRelationship - Compare the two types T1 and T2 to
723/// determine whether they are reference-related,
724/// reference-compatible, reference-compatible with added
725/// qualification, or incompatible, for use in C++ initialization by
726/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
727/// type, and the first type (T1) is the pointee type of the reference
728/// type being initialized.
729Sema::ReferenceCompareResult
730Sema::CompareReferenceRelationship(QualType T1, QualType T2,
731                                   bool& DerivedToBase) {
732  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
733  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
734
735  T1 = Context.getCanonicalType(T1);
736  T2 = Context.getCanonicalType(T2);
737  QualType UnqualT1 = T1.getUnqualifiedType();
738  QualType UnqualT2 = T2.getUnqualifiedType();
739
740  // C++ [dcl.init.ref]p4:
741  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
742  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
743  //   T1 is a base class of T2.
744  if (UnqualT1 == UnqualT2)
745    DerivedToBase = false;
746  else if (IsDerivedFrom(UnqualT2, UnqualT1))
747    DerivedToBase = true;
748  else
749    return Ref_Incompatible;
750
751  // At this point, we know that T1 and T2 are reference-related (at
752  // least).
753
754  // C++ [dcl.init.ref]p4:
755  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
756  //   reference-related to T2 and cv1 is the same cv-qualification
757  //   as, or greater cv-qualification than, cv2. For purposes of
758  //   overload resolution, cases for which cv1 is greater
759  //   cv-qualification than cv2 are identified as
760  //   reference-compatible with added qualification (see 13.3.3.2).
761  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
762    return Ref_Compatible;
763  else if (T1.isMoreQualifiedThan(T2))
764    return Ref_Compatible_With_Added_Qualification;
765  else
766    return Ref_Related;
767}
768
769/// CheckReferenceInit - Check the initialization of a reference
770/// variable with the given initializer (C++ [dcl.init.ref]). Init is
771/// the initializer (either a simple initializer or an initializer
772/// list), and DeclType is the type of the declaration. When ICS is
773/// non-null, this routine will compute the implicit conversion
774/// sequence according to C++ [over.ics.ref] and will not produce any
775/// diagnostics; when ICS is null, it will emit diagnostics when any
776/// errors are found. Either way, a return value of true indicates
777/// that there was a failure, a return value of false indicates that
778/// the reference initialization succeeded.
779bool
780Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
781                         ImplicitConversionSequence *ICS) {
782  assert(DeclType->isReferenceType() && "Reference init needs a reference");
783
784  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
785  QualType T2 = Init->getType();
786
787  // Compute some basic properties of the types and the initializer.
788  bool DerivedToBase = false;
789  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
790  ReferenceCompareResult RefRelationship
791    = CompareReferenceRelationship(T1, T2, DerivedToBase);
792
793  // Most paths end in a failed conversion.
794  if (ICS)
795    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
796
797  // C++ [dcl.init.ref]p5:
798  //   A reference to type “cv1 T1” is initialized by an expression
799  //   of type “cv2 T2” as follows:
800
801  //     -- If the initializer expression
802
803  bool BindsDirectly = false;
804  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
805  //          reference-compatible with “cv2 T2,” or
806  //
807  // Note that the bit-field check is skipped if we are just computing
808  // the implicit conversion sequence (C++ [over.best.ics]p2).
809  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
810      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
811    BindsDirectly = true;
812
813    if (ICS) {
814      // C++ [over.ics.ref]p1:
815      //   When a parameter of reference type binds directly (8.5.3)
816      //   to an argument expression, the implicit conversion sequence
817      //   is the identity conversion, unless the argument expression
818      //   has a type that is a derived class of the parameter type,
819      //   in which case the implicit conversion sequence is a
820      //   derived-to-base Conversion (13.3.3.1).
821      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
822      ICS->Standard.First = ICK_Identity;
823      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
824      ICS->Standard.Third = ICK_Identity;
825      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
826      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
827      ICS->Standard.ReferenceBinding = true;
828      ICS->Standard.DirectBinding = true;
829
830      // Nothing more to do: the inaccessibility/ambiguity check for
831      // derived-to-base conversions is suppressed when we're
832      // computing the implicit conversion sequence (C++
833      // [over.best.ics]p2).
834      return false;
835    } else {
836      // Perform the conversion.
837      // FIXME: Binding to a subobject of the lvalue is going to require
838      // more AST annotation than this.
839      ImpCastExprToType(Init, T1);
840    }
841  }
842
843  //       -- has a class type (i.e., T2 is a class type) and can be
844  //          implicitly converted to an lvalue of type “cv3 T3,”
845  //          where “cv1 T1” is reference-compatible with “cv3 T3”
846  //          92) (this conversion is selected by enumerating the
847  //          applicable conversion functions (13.3.1.6) and choosing
848  //          the best one through overload resolution (13.3)),
849  // FIXME: Implement this second bullet, once we have conversion
850  //        functions. Also remember C++ [over.ics.ref]p1, second part.
851
852  if (BindsDirectly) {
853    // C++ [dcl.init.ref]p4:
854    //   [...] In all cases where the reference-related or
855    //   reference-compatible relationship of two types is used to
856    //   establish the validity of a reference binding, and T1 is a
857    //   base class of T2, a program that necessitates such a binding
858    //   is ill-formed if T1 is an inaccessible (clause 11) or
859    //   ambiguous (10.2) base class of T2.
860    //
861    // Note that we only check this condition when we're allowed to
862    // complain about errors, because we should not be checking for
863    // ambiguity (or inaccessibility) unless the reference binding
864    // actually happens.
865    if (DerivedToBase)
866      return CheckDerivedToBaseConversion(T2, T1,
867                                          Init->getSourceRange().getBegin(),
868                                          Init->getSourceRange());
869    else
870      return false;
871  }
872
873  //     -- Otherwise, the reference shall be to a non-volatile const
874  //        type (i.e., cv1 shall be const).
875  if (T1.getCVRQualifiers() != QualType::Const) {
876    if (!ICS)
877      Diag(Init->getSourceRange().getBegin(),
878           diag::err_not_reference_to_const_init,
879           T1.getAsString(),
880           InitLvalue != Expr::LV_Valid? "temporary" : "value",
881           T2.getAsString(), Init->getSourceRange());
882    return true;
883  }
884
885  //       -- If the initializer expression is an rvalue, with T2 a
886  //          class type, and “cv1 T1” is reference-compatible with
887  //          “cv2 T2,” the reference is bound in one of the
888  //          following ways (the choice is implementation-defined):
889  //
890  //          -- The reference is bound to the object represented by
891  //             the rvalue (see 3.10) or to a sub-object within that
892  //             object.
893  //
894  //          -- A temporary of type “cv1 T2” [sic] is created, and
895  //             a constructor is called to copy the entire rvalue
896  //             object into the temporary. The reference is bound to
897  //             the temporary or to a sub-object within the
898  //             temporary.
899  //
900  //
901  //          The constructor that would be used to make the copy
902  //          shall be callable whether or not the copy is actually
903  //          done.
904  //
905  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
906  // freedom, so we will always take the first option and never build
907  // a temporary in this case. FIXME: We will, however, have to check
908  // for the presence of a copy constructor in C++98/03 mode.
909  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
910      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
911    if (ICS) {
912      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
913      ICS->Standard.First = ICK_Identity;
914      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
915      ICS->Standard.Third = ICK_Identity;
916      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
917      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
918      ICS->Standard.ReferenceBinding = true;
919      ICS->Standard.DirectBinding = false;
920    } else {
921      // FIXME: Binding to a subobject of the rvalue is going to require
922      // more AST annotation than this.
923      ImpCastExprToType(Init, T1);
924    }
925    return false;
926  }
927
928  //       -- Otherwise, a temporary of type “cv1 T1” is created and
929  //          initialized from the initializer expression using the
930  //          rules for a non-reference copy initialization (8.5). The
931  //          reference is then bound to the temporary. If T1 is
932  //          reference-related to T2, cv1 must be the same
933  //          cv-qualification as, or greater cv-qualification than,
934  //          cv2; otherwise, the program is ill-formed.
935  if (RefRelationship == Ref_Related) {
936    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
937    // we would be reference-compatible or reference-compatible with
938    // added qualification. But that wasn't the case, so the reference
939    // initialization fails.
940    if (!ICS)
941      Diag(Init->getSourceRange().getBegin(),
942           diag::err_reference_init_drops_quals,
943           T1.getAsString(),
944           InitLvalue != Expr::LV_Valid? "temporary" : "value",
945           T2.getAsString(), Init->getSourceRange());
946    return true;
947  }
948
949  // Actually try to convert the initializer to T1.
950  if (ICS) {
951    /// C++ [over.ics.ref]p2:
952    ///
953    ///   When a parameter of reference type is not bound directly to
954    ///   an argument expression, the conversion sequence is the one
955    ///   required to convert the argument expression to the
956    ///   underlying type of the reference according to
957    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
958    ///   to copy-initializing a temporary of the underlying type with
959    ///   the argument expression. Any difference in top-level
960    ///   cv-qualification is subsumed by the initialization itself
961    ///   and does not constitute a conversion.
962    *ICS = TryImplicitConversion(Init, T1);
963    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
964  } else {
965    return PerformImplicitConversion(Init, T1);
966  }
967}
968