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