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