SemaCXXScopeSpec.cpp revision 7dfd0fb08300b60a9657748bda7d8b3ceb07babe
1//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
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 C++ semantic analysis for scope specifiers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/NestedNameSpecifier.h"
19#include "clang/Basic/PartialDiagnostic.h"
20#include "clang/Parse/DeclSpec.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Support/raw_ostream.h"
23using namespace clang;
24
25/// \brief Compute the DeclContext that is associated with the given type.
26///
27/// \param T the type for which we are attempting to find a DeclContext.
28///
29/// \returns the declaration context represented by the type T,
30/// or NULL if the declaration context cannot be computed (e.g., because it is
31/// dependent and not the current instantiation).
32DeclContext *Sema::computeDeclContext(QualType T) {
33  if (const TagType *Tag = T->getAs<TagType>())
34    return Tag->getDecl();
35
36  return 0;
37}
38
39/// \brief Compute the DeclContext that is associated with the given
40/// scope specifier.
41///
42/// \param SS the C++ scope specifier as it appears in the source
43///
44/// \param EnteringContext when true, we will be entering the context of
45/// this scope specifier, so we can retrieve the declaration context of a
46/// class template or class template partial specialization even if it is
47/// not the current instantiation.
48///
49/// \returns the declaration context represented by the scope specifier @p SS,
50/// or NULL if the declaration context cannot be computed (e.g., because it is
51/// dependent and not the current instantiation).
52DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
53                                      bool EnteringContext) {
54  if (!SS.isSet() || SS.isInvalid())
55    return 0;
56
57  NestedNameSpecifier *NNS
58    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
59  if (NNS->isDependent()) {
60    // If this nested-name-specifier refers to the current
61    // instantiation, return its DeclContext.
62    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
63      return Record;
64
65    if (EnteringContext) {
66      if (const TemplateSpecializationType *SpecType
67            = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
68        // We are entering the context of the nested name specifier, so try to
69        // match the nested name specifier to either a primary class template
70        // or a class template partial specialization.
71        if (ClassTemplateDecl *ClassTemplate
72              = dyn_cast_or_null<ClassTemplateDecl>(
73                            SpecType->getTemplateName().getAsTemplateDecl())) {
74          QualType ContextType
75            = Context.getCanonicalType(QualType(SpecType, 0));
76
77          // If the type of the nested name specifier is the same as the
78          // injected class name of the named class template, we're entering
79          // into that class template definition.
80          QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
81          if (Context.hasSameType(Injected, ContextType))
82            return ClassTemplate->getTemplatedDecl();
83
84          // If the type of the nested name specifier is the same as the
85          // type of one of the class template's class template partial
86          // specializations, we're entering into the definition of that
87          // class template partial specialization.
88          if (ClassTemplatePartialSpecializationDecl *PartialSpec
89                = ClassTemplate->findPartialSpecialization(ContextType))
90            return PartialSpec;
91        }
92      } else if (const RecordType *RecordT
93                   = dyn_cast_or_null<RecordType>(NNS->getAsType())) {
94        // The nested name specifier refers to a member of a class template.
95        return RecordT->getDecl();
96      }
97    }
98
99    return 0;
100  }
101
102  switch (NNS->getKind()) {
103  case NestedNameSpecifier::Identifier:
104    assert(false && "Dependent nested-name-specifier has no DeclContext");
105    break;
106
107  case NestedNameSpecifier::Namespace:
108    return NNS->getAsNamespace();
109
110  case NestedNameSpecifier::TypeSpec:
111  case NestedNameSpecifier::TypeSpecWithTemplate: {
112    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
113    assert(Tag && "Non-tag type in nested-name-specifier");
114    return Tag->getDecl();
115  } break;
116
117  case NestedNameSpecifier::Global:
118    return Context.getTranslationUnitDecl();
119  }
120
121  // Required to silence a GCC warning.
122  return 0;
123}
124
125bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
126  if (!SS.isSet() || SS.isInvalid())
127    return false;
128
129  NestedNameSpecifier *NNS
130    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
131  return NNS->isDependent();
132}
133
134// \brief Determine whether this C++ scope specifier refers to an
135// unknown specialization, i.e., a dependent type that is not the
136// current instantiation.
137bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
138  if (!isDependentScopeSpecifier(SS))
139    return false;
140
141  NestedNameSpecifier *NNS
142    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
143  return getCurrentInstantiationOf(NNS) == 0;
144}
145
146/// \brief If the given nested name specifier refers to the current
147/// instantiation, return the declaration that corresponds to that
148/// current instantiation (C++0x [temp.dep.type]p1).
149///
150/// \param NNS a dependent nested name specifier.
151CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
152  assert(getLangOptions().CPlusPlus && "Only callable in C++");
153  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
154
155  if (!NNS->getAsType())
156    return 0;
157
158  QualType T = QualType(NNS->getAsType(), 0);
159  // If the nested name specifier does not refer to a type, then it
160  // does not refer to the current instantiation.
161  if (T.isNull())
162    return 0;
163
164  T = Context.getCanonicalType(T);
165
166  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
167    // If we've hit a namespace or the global scope, then the
168    // nested-name-specifier can't refer to the current instantiation.
169    if (Ctx->isFileContext())
170      return 0;
171
172    // Skip non-class contexts.
173    CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
174    if (!Record)
175      continue;
176
177    // If this record type is not dependent,
178    if (!Record->isDependentType())
179      return 0;
180
181    // C++ [temp.dep.type]p1:
182    //
183    //   In the definition of a class template, a nested class of a
184    //   class template, a member of a class template, or a member of a
185    //   nested class of a class template, a name refers to the current
186    //   instantiation if it is
187    //     -- the injected-class-name (9) of the class template or
188    //        nested class,
189    //     -- in the definition of a primary class template, the name
190    //        of the class template followed by the template argument
191    //        list of the primary template (as described below)
192    //        enclosed in <>,
193    //     -- in the definition of a nested class of a class template,
194    //        the name of the nested class referenced as a member of
195    //        the current instantiation, or
196    //     -- in the definition of a partial specialization, the name
197    //        of the class template followed by the template argument
198    //        list of the partial specialization enclosed in <>. If
199    //        the nth template parameter is a parameter pack, the nth
200    //        template argument is a pack expansion (14.6.3) whose
201    //        pattern is the name of the parameter pack.
202    //        (FIXME: parameter packs)
203    //
204    // All of these options come down to having the
205    // nested-name-specifier type that is equivalent to the
206    // injected-class-name of one of the types that is currently in
207    // our context.
208    if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
209      return Record;
210
211    if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
212      QualType InjectedClassName
213        = Template->getInjectedClassNameType(Context);
214      if (T == Context.getCanonicalType(InjectedClassName))
215        return Template->getTemplatedDecl();
216    }
217    // FIXME: check for class template partial specializations
218  }
219
220  return 0;
221}
222
223/// \brief Require that the context specified by SS be complete.
224///
225/// If SS refers to a type, this routine checks whether the type is
226/// complete enough (or can be made complete enough) for name lookup
227/// into the DeclContext. A type that is not yet completed can be
228/// considered "complete enough" if it is a class/struct/union/enum
229/// that is currently being defined. Or, if we have a type that names
230/// a class template specialization that is not a complete type, we
231/// will attempt to instantiate that class template.
232bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
233  if (!SS.isSet() || SS.isInvalid())
234    return false;
235
236  DeclContext *DC = computeDeclContext(SS, true);
237  if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
238    // If we're currently defining this type, then lookup into the
239    // type is okay: don't complain that it isn't complete yet.
240    const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
241    if (TagT->isBeingDefined())
242      return false;
243
244    // The type must be complete.
245    return RequireCompleteType(SS.getRange().getBegin(),
246                               Context.getTypeDeclType(Tag),
247                               PDiag(diag::err_incomplete_nested_name_spec)
248                                 << SS.getRange());
249  }
250
251  return false;
252}
253
254/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
255/// global scope ('::').
256Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
257                                                     SourceLocation CCLoc) {
258  return NestedNameSpecifier::GlobalSpecifier(Context);
259}
260
261/// \brief Determines whether the given declaration is an valid acceptable
262/// result for name lookup of a nested-name-specifier.
263bool Sema::isAcceptableNestedNameSpecifier(NamedDecl *SD) {
264  if (!SD)
265    return false;
266
267  // Namespace and namespace aliases are fine.
268  if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
269    return true;
270
271  if (!isa<TypeDecl>(SD))
272    return false;
273
274  // Determine whether we have a class (or, in C++0x, an enum) or
275  // a typedef thereof. If so, build the nested-name-specifier.
276  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
277  if (T->isDependentType())
278    return true;
279  else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
280    if (TD->getUnderlyingType()->isRecordType() ||
281        (Context.getLangOptions().CPlusPlus0x &&
282         TD->getUnderlyingType()->isEnumeralType()))
283      return true;
284  } else if (isa<RecordDecl>(SD) ||
285             (Context.getLangOptions().CPlusPlus0x && isa<EnumDecl>(SD)))
286    return true;
287
288  return false;
289}
290
291/// \brief If the given nested-name-specifier begins with a bare identifier
292/// (e.g., Base::), perform name lookup for that identifier as a
293/// nested-name-specifier within the given scope, and return the result of that
294/// name lookup.
295NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
296  if (!S || !NNS)
297    return 0;
298
299  while (NNS->getPrefix())
300    NNS = NNS->getPrefix();
301
302  if (NNS->getKind() != NestedNameSpecifier::Identifier)
303    return 0;
304
305  LookupResult Found
306    = LookupName(S, NNS->getAsIdentifier(), LookupNestedNameSpecifierName);
307  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
308
309  NamedDecl *Result = Found;
310  if (isAcceptableNestedNameSpecifier(Result))
311    return Result;
312
313  return 0;
314}
315
316/// \brief Build a new nested-name-specifier for "identifier::", as described
317/// by ActOnCXXNestedNameSpecifier.
318///
319/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
320/// that it contains an extra parameter \p ScopeLookupResult, which provides
321/// the result of name lookup within the scope of the nested-name-specifier
322/// that was computed at template definitino time.
323Sema::CXXScopeTy *Sema::BuildCXXNestedNameSpecifier(Scope *S,
324                                                    const CXXScopeSpec &SS,
325                                                    SourceLocation IdLoc,
326                                                    SourceLocation CCLoc,
327                                                    IdentifierInfo &II,
328                                                    QualType ObjectType,
329                                                  NamedDecl *ScopeLookupResult,
330                                                    bool EnteringContext) {
331  NestedNameSpecifier *Prefix
332    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
333
334  // Determine where to perform name lookup
335  DeclContext *LookupCtx = 0;
336  bool isDependent = false;
337  if (!ObjectType.isNull()) {
338    // This nested-name-specifier occurs in a member access expression, e.g.,
339    // x->B::f, and we are looking into the type of the object.
340    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
341    LookupCtx = computeDeclContext(ObjectType);
342    isDependent = ObjectType->isDependentType();
343  } else if (SS.isSet()) {
344    // This nested-name-specifier occurs after another nested-name-specifier,
345    // so long into the context associated with the prior nested-name-specifier.
346    LookupCtx = computeDeclContext(SS, EnteringContext);
347    isDependent = isDependentScopeSpecifier(SS);
348  }
349
350  LookupResult Found;
351  bool ObjectTypeSearchedInScope = false;
352  if (LookupCtx) {
353    // Perform "qualified" name lookup into the declaration context we
354    // computed, which is either the type of the base of a member access
355    // expression or the declaration context associated with a prior
356    // nested-name-specifier.
357
358    // The declaration context must be complete.
359    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(SS))
360      return 0;
361
362    Found = LookupQualifiedName(LookupCtx, &II, LookupNestedNameSpecifierName,
363                                false);
364
365    if (!ObjectType.isNull() && Found.getKind() == LookupResult::NotFound) {
366      // C++ [basic.lookup.classref]p4:
367      //   If the id-expression in a class member access is a qualified-id of
368      //   the form
369      //
370      //        class-name-or-namespace-name::...
371      //
372      //   the class-name-or-namespace-name following the . or -> operator is
373      //   looked up both in the context of the entire postfix-expression and in
374      //   the scope of the class of the object expression. If the name is found
375      //   only in the scope of the class of the object expression, the name
376      //   shall refer to a class-name. If the name is found only in the
377      //   context of the entire postfix-expression, the name shall refer to a
378      //   class-name or namespace-name. [...]
379      //
380      // Qualified name lookup into a class will not find a namespace-name,
381      // so we do not need to diagnoste that case specifically. However,
382      // this qualified name lookup may find nothing. In that case, perform
383      // unqualified name lookup in the given scope (if available) or
384      // reconstruct the result from when name lookup was performed at template
385      // definition time.
386      if (S)
387        Found = LookupName(S, &II, LookupNestedNameSpecifierName);
388      else
389        Found = LookupResult::CreateLookupResult(Context, ScopeLookupResult);
390
391      ObjectTypeSearchedInScope = true;
392    }
393  } else if (isDependent) {
394    // We were not able to compute the declaration context for a dependent
395    // base object type or prior nested-name-specifier, so this
396    // nested-name-specifier refers to an unknown specialization. Just build
397    // a dependent nested-name-specifier.
398    if (!Prefix)
399      return NestedNameSpecifier::Create(Context, &II);
400
401    return NestedNameSpecifier::Create(Context, Prefix, &II);
402  } else {
403    // Perform unqualified name lookup in the current scope.
404    Found = LookupName(S, &II, LookupNestedNameSpecifierName);
405  }
406
407  // FIXME: Deal with ambiguities cleanly.
408  NamedDecl *SD = Found;
409  if (isAcceptableNestedNameSpecifier(SD)) {
410    if (!ObjectType.isNull() && !ObjectTypeSearchedInScope) {
411      // C++ [basic.lookup.classref]p4:
412      //   [...] If the name is found in both contexts, the
413      //   class-name-or-namespace-name shall refer to the same entity.
414      //
415      // We already found the name in the scope of the object. Now, look
416      // into the current scope (the scope of the postfix-expression) to
417      // see if we can find the same name there. As above, if there is no
418      // scope, reconstruct the result from the template instantiation itself.
419      LookupResult FoundOuter;
420      if (S)
421        FoundOuter = LookupName(S, &II, LookupNestedNameSpecifierName);
422      else
423        FoundOuter = LookupResult::CreateLookupResult(Context,
424                                                      ScopeLookupResult);
425
426      // FIXME: Handle ambiguities in FoundOuter!
427      NamedDecl *OuterDecl = FoundOuter;
428      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
429          OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
430          (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
431           !Context.hasSameType(
432                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
433                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
434             Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
435               << &II;
436             Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
437               << ObjectType;
438             Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
439
440             // Fall through so that we'll pick the name we found in the object type,
441             // since that's probably what the user wanted anyway.
442           }
443    }
444
445    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
446      return NestedNameSpecifier::Create(Context, Prefix, Namespace);
447
448    // FIXME: It would be nice to maintain the namespace alias name, then
449    // see through that alias when resolving the nested-name-specifier down to
450    // a declaration context.
451    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
452      return NestedNameSpecifier::Create(Context, Prefix,
453
454                                         Alias->getNamespace());
455
456    QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
457    return NestedNameSpecifier::Create(Context, Prefix, false,
458                                       T.getTypePtr());
459  }
460
461  // If we didn't find anything during our lookup, try again with
462  // ordinary name lookup, which can help us produce better error
463  // messages.
464  if (!SD)
465    SD = LookupName(S, &II, LookupOrdinaryName);
466
467  unsigned DiagID;
468  if (SD)
469    DiagID = diag::err_expected_class_or_namespace;
470  else if (SS.isSet()) {
471    DiagnoseMissingMember(IdLoc, DeclarationName(&II),
472                          (NestedNameSpecifier *)SS.getScopeRep(),
473                          SS.getRange());
474    return 0;
475  } else
476    DiagID = diag::err_undeclared_var_use;
477
478  if (SS.isSet())
479    Diag(IdLoc, DiagID) << &II << SS.getRange();
480  else
481    Diag(IdLoc, DiagID) << &II;
482
483  return 0;
484}
485
486/// ActOnCXXNestedNameSpecifier - Called during parsing of a
487/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
488/// we want to resolve "bar::". 'SS' is empty or the previously parsed
489/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
490/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
491/// Returns a CXXScopeTy* object representing the C++ scope.
492Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
493                                                    const CXXScopeSpec &SS,
494                                                    SourceLocation IdLoc,
495                                                    SourceLocation CCLoc,
496                                                    IdentifierInfo &II,
497                                                    TypeTy *ObjectTypePtr,
498                                                    bool EnteringContext) {
499  return BuildCXXNestedNameSpecifier(S, SS, IdLoc, CCLoc, II,
500                                     QualType::getFromOpaquePtr(ObjectTypePtr),
501                                     /*ScopeLookupResult=*/0, EnteringContext);
502}
503
504Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
505                                                    const CXXScopeSpec &SS,
506                                                    TypeTy *Ty,
507                                                    SourceRange TypeRange,
508                                                    SourceLocation CCLoc) {
509  NestedNameSpecifier *Prefix
510    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
511  QualType T = GetTypeFromParser(Ty);
512  return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
513                                     T.getTypePtr());
514}
515
516/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
517/// scope or nested-name-specifier) is parsed, part of a declarator-id.
518/// After this method is called, according to [C++ 3.4.3p3], names should be
519/// looked up in the declarator-id's scope, until the declarator is parsed and
520/// ActOnCXXExitDeclaratorScope is called.
521/// The 'SS' should be a non-empty valid CXXScopeSpec.
522bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
523  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
524  if (DeclContext *DC = computeDeclContext(SS, true)) {
525    // Before we enter a declarator's context, we need to make sure that
526    // it is a complete declaration context.
527    if (!DC->isDependentContext() && RequireCompleteDeclContext(SS))
528      return true;
529
530    EnterDeclaratorContext(S, DC);
531  }
532
533  return false;
534}
535
536/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
537/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
538/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
539/// Used to indicate that names should revert to being looked up in the
540/// defining scope.
541void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
542  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
543  if (SS.isInvalid())
544    return;
545  if (computeDeclContext(SS, true))
546    ExitDeclaratorContext(S);
547}
548