SemaCXXScopeSpec.cpp revision 84a20812c8204f2210622729b8a41e53170baaad
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/NestedNameSpecifier.h"
18#include "clang/Parse/DeclSpec.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/raw_ostream.h"
21using namespace clang;
22
23/// \brief Compute the DeclContext that is associated with the given
24/// scope specifier.
25///
26/// \param SS the C++ scope specifier as it appears in the source
27///
28/// \param EnteringContext when true, we will be entering the context of
29/// this scope specifier, so we can retrieve the declaration context of a
30/// class template or class template partial specialization even if it is
31/// not the current instantiation.
32///
33/// \returns the declaration context represented by the scope specifier @p SS,
34/// or NULL if the declaration context cannot be computed (e.g., because it is
35/// dependent and not the current instantiation).
36DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
37                                      bool EnteringContext) {
38  if (!SS.isSet() || SS.isInvalid())
39    return 0;
40
41  NestedNameSpecifier *NNS
42    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
43  if (NNS->isDependent()) {
44    // If this nested-name-specifier refers to the current
45    // instantiation, return its DeclContext.
46    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
47      return Record;
48
49    if (EnteringContext) {
50      // We are entering the context of the nested name specifier, so try to
51      // match the nested name specifier to either a primary class template
52      // or a class template partial specialization.
53      if (const TemplateSpecializationType *SpecType
54            = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
55        if (ClassTemplateDecl *ClassTemplate
56              = dyn_cast_or_null<ClassTemplateDecl>(
57                            SpecType->getTemplateName().getAsTemplateDecl())) {
58          // If the type of the nested name specifier is the same as the
59          // injected class name of the named class template, we're entering
60          // into that class template definition.
61          QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
62          if (Context.hasSameType(Injected, QualType(SpecType, 0)))
63            return ClassTemplate->getTemplatedDecl();
64
65          // FIXME: Class template partial specializations
66        }
67      }
68
69      std::string NNSString;
70      {
71        llvm::raw_string_ostream OS(NNSString);
72        NNS->print(OS, Context.PrintingPolicy);
73      }
74
75      // FIXME: Allow us to pass a nested-name-specifier to Diag?
76      Diag(SS.getRange().getBegin(),
77           diag::err_template_qualified_declarator_no_match)
78        << NNSString << SS.getRange();
79    }
80
81    return 0;
82  }
83
84  switch (NNS->getKind()) {
85  case NestedNameSpecifier::Identifier:
86    assert(false && "Dependent nested-name-specifier has no DeclContext");
87    break;
88
89  case NestedNameSpecifier::Namespace:
90    return NNS->getAsNamespace();
91
92  case NestedNameSpecifier::TypeSpec:
93  case NestedNameSpecifier::TypeSpecWithTemplate: {
94    const TagType *Tag = NNS->getAsType()->getAsTagType();
95    assert(Tag && "Non-tag type in nested-name-specifier");
96    return Tag->getDecl();
97  } break;
98
99  case NestedNameSpecifier::Global:
100    return Context.getTranslationUnitDecl();
101  }
102
103  // Required to silence a GCC warning.
104  return 0;
105}
106
107bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
108  if (!SS.isSet() || SS.isInvalid())
109    return false;
110
111  NestedNameSpecifier *NNS
112    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
113  return NNS->isDependent();
114}
115
116// \brief Determine whether this C++ scope specifier refers to an
117// unknown specialization, i.e., a dependent type that is not the
118// current instantiation.
119bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
120  if (!isDependentScopeSpecifier(SS))
121    return false;
122
123  NestedNameSpecifier *NNS
124    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
125  return getCurrentInstantiationOf(NNS) == 0;
126}
127
128/// \brief If the given nested name specifier refers to the current
129/// instantiation, return the declaration that corresponds to that
130/// current instantiation (C++0x [temp.dep.type]p1).
131///
132/// \param NNS a dependent nested name specifier.
133CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
134  assert(getLangOptions().CPlusPlus && "Only callable in C++");
135  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
136
137  if (!NNS->getAsType())
138    return 0;
139
140  QualType T = Context.getCanonicalType(QualType(NNS->getAsType(), 0));
141  // If the nested name specifier does not refer to a type, then it
142  // does not refer to the current instantiation.
143  if (T.isNull())
144    return 0;
145
146  T = Context.getCanonicalType(T);
147
148  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
149    // If we've hit a namespace or the global scope, then the
150    // nested-name-specifier can't refer to the current instantiation.
151    if (Ctx->isFileContext())
152      return 0;
153
154    // Skip non-class contexts.
155    CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
156    if (!Record)
157      continue;
158
159    // If this record type is not dependent,
160    if (!Record->isDependentType())
161      return 0;
162
163    // C++ [temp.dep.type]p1:
164    //
165    //   In the definition of a class template, a nested class of a
166    //   class template, a member of a class template, or a member of a
167    //   nested class of a class template, a name refers to the current
168    //   instantiation if it is
169    //     -- the injected-class-name (9) of the class template or
170    //        nested class,
171    //     -- in the definition of a primary class template, the name
172    //        of the class template followed by the template argument
173    //        list of the primary template (as described below)
174    //        enclosed in <>,
175    //     -- in the definition of a nested class of a class template,
176    //        the name of the nested class referenced as a member of
177    //        the current instantiation, or
178    //     -- in the definition of a partial specialization, the name
179    //        of the class template followed by the template argument
180    //        list of the partial specialization enclosed in <>. If
181    //        the nth template parameter is a parameter pack, the nth
182    //        template argument is a pack expansion (14.6.3) whose
183    //        pattern is the name of the parameter pack. (FIXME)
184    //
185    // All of these options come down to having the
186    // nested-name-specifier type that is equivalent to the
187    // injected-class-name of one of the types that is currently in
188    // our context.
189    if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
190      return Record;
191
192    if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
193      QualType InjectedClassName
194        = Template->getInjectedClassNameType(Context);
195      if (T == Context.getCanonicalType(InjectedClassName))
196        return Template->getTemplatedDecl();
197    }
198  }
199
200  return 0;
201}
202
203/// \brief Require that the context specified by SS be complete.
204///
205/// If SS refers to a type, this routine checks whether the type is
206/// complete enough (or can be made complete enough) for name lookup
207/// into the DeclContext. A type that is not yet completed can be
208/// considered "complete enough" if it is a class/struct/union/enum
209/// that is currently being defined. Or, if we have a type that names
210/// a class template specialization that is not a complete type, we
211/// will attempt to instantiate that class template.
212bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
213  if (!SS.isSet() || SS.isInvalid())
214    return false;
215
216  DeclContext *DC = computeDeclContext(SS, true);
217  if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
218    // If we're currently defining this type, then lookup into the
219    // type is okay: don't complain that it isn't complete yet.
220    const TagType *TagT = Context.getTypeDeclType(Tag)->getAsTagType();
221    if (TagT->isBeingDefined())
222      return false;
223
224    // The type must be complete.
225    return RequireCompleteType(SS.getRange().getBegin(),
226                               Context.getTypeDeclType(Tag),
227                               diag::err_incomplete_nested_name_spec,
228                               SS.getRange());
229  }
230
231  return false;
232}
233
234/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
235/// global scope ('::').
236Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
237                                                     SourceLocation CCLoc) {
238  return NestedNameSpecifier::GlobalSpecifier(Context);
239}
240
241/// ActOnCXXNestedNameSpecifier - Called during parsing of a
242/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
243/// we want to resolve "bar::". 'SS' is empty or the previously parsed
244/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
245/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
246/// Returns a CXXScopeTy* object representing the C++ scope.
247Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
248                                                    const CXXScopeSpec &SS,
249                                                    SourceLocation IdLoc,
250                                                    SourceLocation CCLoc,
251                                                    IdentifierInfo &II) {
252  NestedNameSpecifier *Prefix
253    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
254
255  // If the prefix already refers to an unknown specialization, there
256  // is no name lookup to perform. Just build the resulting
257  // nested-name-specifier.
258  if (Prefix && isUnknownSpecialization(SS))
259    return NestedNameSpecifier::Create(Context, Prefix, &II);
260
261  NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
262
263  if (SD) {
264    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
265      return NestedNameSpecifier::Create(Context, Prefix, Namespace);
266
267    if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
268      // Determine whether we have a class (or, in C++0x, an enum) or
269      // a typedef thereof. If so, build the nested-name-specifier.
270      QualType T = Context.getTypeDeclType(Type);
271      bool AcceptableType = false;
272      if (T->isDependentType())
273        AcceptableType = true;
274      else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
275        if (TD->getUnderlyingType()->isRecordType() ||
276            (getLangOptions().CPlusPlus0x &&
277             TD->getUnderlyingType()->isEnumeralType()))
278          AcceptableType = true;
279      } else if (isa<RecordDecl>(Type) ||
280                 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
281        AcceptableType = true;
282
283      if (AcceptableType)
284        return NestedNameSpecifier::Create(Context, Prefix, false,
285                                           T.getTypePtr());
286    }
287
288    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
289      return NestedNameSpecifier::Create(Context, Prefix,
290                                         Alias->getNamespace());
291
292    // Fall through to produce an error: we found something that isn't
293    // a class or a namespace.
294  }
295
296  // If we didn't find anything during our lookup, try again with
297  // ordinary name lookup, which can help us produce better error
298  // messages.
299  if (!SD)
300    SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName);
301  unsigned DiagID;
302  if (SD)
303    DiagID = diag::err_expected_class_or_namespace;
304  else if (SS.isSet())
305    DiagID = diag::err_typecheck_no_member;
306  else
307    DiagID = diag::err_undeclared_var_use;
308
309  if (SS.isSet())
310    Diag(IdLoc, DiagID) << &II << SS.getRange();
311  else
312    Diag(IdLoc, DiagID) << &II;
313
314  return 0;
315}
316
317Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
318                                                    const CXXScopeSpec &SS,
319                                                    TypeTy *Ty,
320                                                    SourceRange TypeRange,
321                                                    SourceLocation CCLoc) {
322  NestedNameSpecifier *Prefix
323    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
324  QualType T = QualType::getFromOpaquePtr(Ty);
325  return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
326                                     T.getTypePtr());
327}
328
329/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
330/// scope or nested-name-specifier) is parsed, part of a declarator-id.
331/// After this method is called, according to [C++ 3.4.3p3], names should be
332/// looked up in the declarator-id's scope, until the declarator is parsed and
333/// ActOnCXXExitDeclaratorScope is called.
334/// The 'SS' should be a non-empty valid CXXScopeSpec.
335void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
336  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
337  if (DeclContext *DC = computeDeclContext(SS, true))
338    EnterDeclaratorContext(S, DC);
339  else
340    const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
341}
342
343/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
344/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
345/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
346/// Used to indicate that names should revert to being looked up in the
347/// defining scope.
348void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
349  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
350  assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
351         "Context imbalance!");
352  if (!SS.isInvalid())
353    ExitDeclaratorContext(S);
354}
355