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