blob: 7db0da45535e106a18b76d51d8f7f9ce8da68b2d [file] [log] [blame]
Cedric Venet3d658642009-02-14 20:20:19 +00001//===--- 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"
Douglas Gregor42af25f2009-05-11 19:58:34 +000016#include "clang/AST/DeclTemplate.h"
Douglas Gregore4e5b052009-03-19 00:18:19 +000017#include "clang/AST/NestedNameSpecifier.h"
Cedric Venet3d658642009-02-14 20:20:19 +000018#include "clang/Parse/DeclSpec.h"
19#include "llvm/ADT/STLExtras.h"
20using namespace clang;
21
Douglas Gregore4e5b052009-03-19 00:18:19 +000022/// \brief Compute the DeclContext that is associated with the given
23/// scope specifier.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000024///
25/// \param SS the C++ scope specifier as it appears in the source
26///
27/// \param EnteringContext when true, we will be entering the context of
28/// this scope specifier, so we can retrieve the declaration context of a
29/// class template or class template partial specialization even if it is
30/// not the current instantiation.
31///
32/// \returns the declaration context represented by the scope specifier @p SS,
33/// or NULL if the declaration context cannot be computed (e.g., because it is
34/// dependent and not the current instantiation).
35DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
36 bool EnteringContext) {
Douglas Gregore4e5b052009-03-19 00:18:19 +000037 if (!SS.isSet() || SS.isInvalid())
Douglas Gregorca5e77f2009-03-18 00:36:05 +000038 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +000039
Douglas Gregorab452ba2009-03-26 23:50:42 +000040 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +000041 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor42af25f2009-05-11 19:58:34 +000042 if (NNS->isDependent()) {
43 // If this nested-name-specifier refers to the current
44 // instantiation, return its DeclContext.
45 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
46 return Record;
Douglas Gregorf59a56e2009-07-21 23:53:31 +000047
48 if (EnteringContext) {
49 // We are entering the context of the nested name specifier, so try to
50 // match the nested name specifier to either a primary class template
51 // or a class template partial specialization
52 if (const TemplateSpecializationType *SpecType
53 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
54 if (ClassTemplateDecl *ClassTemplate
55 = dyn_cast_or_null<ClassTemplateDecl>(
56 SpecType->getTemplateName().getAsTemplateDecl())) {
57 // If the type of the nested name specifier is the same as the
58 // injected class name of the named class template, we're entering
59 // into that class template definition.
60 QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
61 if (Context.hasSameType(Injected, QualType(SpecType, 0)))
62 return ClassTemplate->getTemplatedDecl();
63
64 // FIXME: Class template partial specializations
65 }
66 }
67 }
68
69 return 0;
Douglas Gregor42af25f2009-05-11 19:58:34 +000070 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000071
72 switch (NNS->getKind()) {
73 case NestedNameSpecifier::Identifier:
74 assert(false && "Dependent nested-name-specifier has no DeclContext");
75 break;
76
77 case NestedNameSpecifier::Namespace:
78 return NNS->getAsNamespace();
79
80 case NestedNameSpecifier::TypeSpec:
81 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenek35366a62009-07-17 17:50:17 +000082 const TagType *Tag = NNS->getAsType()->getAsTagType();
Douglas Gregorab452ba2009-03-26 23:50:42 +000083 assert(Tag && "Non-tag type in nested-name-specifier");
84 return Tag->getDecl();
85 } break;
86
87 case NestedNameSpecifier::Global:
88 return Context.getTranslationUnitDecl();
89 }
90
91 // Required to silence a GCC warning.
92 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +000093}
94
Douglas Gregor5953d8b2009-03-19 17:26:29 +000095bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
96 if (!SS.isSet() || SS.isInvalid())
97 return false;
98
Douglas Gregorab452ba2009-03-26 23:50:42 +000099 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +0000100 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000101 return NNS->isDependent();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000102}
103
Douglas Gregor42af25f2009-05-11 19:58:34 +0000104// \brief Determine whether this C++ scope specifier refers to an
105// unknown specialization, i.e., a dependent type that is not the
106// current instantiation.
107bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
108 if (!isDependentScopeSpecifier(SS))
109 return false;
110
111 NestedNameSpecifier *NNS
112 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
113 return getCurrentInstantiationOf(NNS) == 0;
114}
115
116/// \brief If the given nested name specifier refers to the current
117/// instantiation, return the declaration that corresponds to that
118/// current instantiation (C++0x [temp.dep.type]p1).
119///
120/// \param NNS a dependent nested name specifier.
121CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
122 assert(getLangOptions().CPlusPlus && "Only callable in C++");
123 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
124
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000125 if (!NNS->getAsType())
126 return 0;
127
128 QualType T = Context.getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor42af25f2009-05-11 19:58:34 +0000129 // If the nested name specifier does not refer to a type, then it
130 // does not refer to the current instantiation.
131 if (T.isNull())
132 return 0;
133
134 T = Context.getCanonicalType(T);
135
136 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
137 // If we've hit a namespace or the global scope, then the
138 // nested-name-specifier can't refer to the current instantiation.
139 if (Ctx->isFileContext())
140 return 0;
141
142 // Skip non-class contexts.
143 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
144 if (!Record)
145 continue;
146
147 // If this record type is not dependent,
148 if (!Record->isDependentType())
149 return 0;
150
151 // C++ [temp.dep.type]p1:
152 //
153 // In the definition of a class template, a nested class of a
154 // class template, a member of a class template, or a member of a
155 // nested class of a class template, a name refers to the current
156 // instantiation if it is
157 // -- the injected-class-name (9) of the class template or
158 // nested class,
159 // -- in the definition of a primary class template, the name
160 // of the class template followed by the template argument
161 // list of the primary template (as described below)
162 // enclosed in <>,
163 // -- in the definition of a nested class of a class template,
164 // the name of the nested class referenced as a member of
165 // the current instantiation, or
166 // -- in the definition of a partial specialization, the name
167 // of the class template followed by the template argument
168 // list of the partial specialization enclosed in <>. If
169 // the nth template parameter is a parameter pack, the nth
170 // template argument is a pack expansion (14.6.3) whose
171 // pattern is the name of the parameter pack. (FIXME)
172 //
173 // All of these options come down to having the
174 // nested-name-specifier type that is equivalent to the
175 // injected-class-name of one of the types that is currently in
176 // our context.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000177 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000178 return Record;
179
180 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
181 QualType InjectedClassName
182 = Template->getInjectedClassNameType(Context);
183 if (T == Context.getCanonicalType(InjectedClassName))
184 return Template->getTemplatedDecl();
185 }
186 }
187
188 return 0;
189}
190
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000191/// \brief Require that the context specified by SS be complete.
192///
193/// If SS refers to a type, this routine checks whether the type is
194/// complete enough (or can be made complete enough) for name lookup
195/// into the DeclContext. A type that is not yet completed can be
196/// considered "complete enough" if it is a class/struct/union/enum
197/// that is currently being defined. Or, if we have a type that names
198/// a class template specialization that is not a complete type, we
199/// will attempt to instantiate that class template.
200bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
201 if (!SS.isSet() || SS.isInvalid())
202 return false;
203
Douglas Gregore4e5b052009-03-19 00:18:19 +0000204 DeclContext *DC = computeDeclContext(SS);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000205 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
206 // If we're currently defining this type, then lookup into the
207 // type is okay: don't complain that it isn't complete yet.
Ted Kremenek35366a62009-07-17 17:50:17 +0000208 const TagType *TagT = Context.getTypeDeclType(Tag)->getAsTagType();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000209 if (TagT->isBeingDefined())
210 return false;
211
212 // The type must be complete.
213 return RequireCompleteType(SS.getRange().getBegin(),
214 Context.getTypeDeclType(Tag),
215 diag::err_incomplete_nested_name_spec,
216 SS.getRange());
217 }
218
219 return false;
220}
Cedric Venet3d658642009-02-14 20:20:19 +0000221
222/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
223/// global scope ('::').
224Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
225 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000226 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000227}
228
229/// ActOnCXXNestedNameSpecifier - Called during parsing of a
230/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
231/// we want to resolve "bar::". 'SS' is empty or the previously parsed
232/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
233/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
234/// Returns a CXXScopeTy* object representing the C++ scope.
235Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
236 const CXXScopeSpec &SS,
237 SourceLocation IdLoc,
238 SourceLocation CCLoc,
239 IdentifierInfo &II) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000240 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000241 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000242
Douglas Gregor42af25f2009-05-11 19:58:34 +0000243 // If the prefix already refers to an unknown specialization, there
244 // is no name lookup to perform. Just build the resulting
245 // nested-name-specifier.
246 if (Prefix && isUnknownSpecialization(SS))
Douglas Gregorab452ba2009-03-26 23:50:42 +0000247 return NestedNameSpecifier::Create(Context, Prefix, &II);
248
Cedric Venet3d658642009-02-14 20:20:19 +0000249 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
250
251 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000252 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
253 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000254
Douglas Gregorab452ba2009-03-26 23:50:42 +0000255 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
256 // Determine whether we have a class (or, in C++0x, an enum) or
257 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord57959a2009-03-27 23:10:48 +0000258 QualType T = Context.getTypeDeclType(Type);
259 bool AcceptableType = false;
260 if (T->isDependentType())
261 AcceptableType = true;
262 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000263 if (TD->getUnderlyingType()->isRecordType() ||
264 (getLangOptions().CPlusPlus0x &&
265 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000266 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000267 } else if (isa<RecordDecl>(Type) ||
268 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000269 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000270
Douglas Gregord57959a2009-03-27 23:10:48 +0000271 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000272 return NestedNameSpecifier::Create(Context, Prefix, false,
273 T.getTypePtr());
274 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000275
276 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
277 return NestedNameSpecifier::Create(Context, Prefix,
278 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000279
280 // Fall through to produce an error: we found something that isn't
281 // a class or a namespace.
282 }
283
284 // If we didn't find anything during our lookup, try again with
285 // ordinary name lookup, which can help us produce better error
286 // messages.
287 if (!SD)
288 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName);
289 unsigned DiagID;
290 if (SD)
291 DiagID = diag::err_expected_class_or_namespace;
292 else if (SS.isSet())
293 DiagID = diag::err_typecheck_no_member;
294 else
295 DiagID = diag::err_undeclared_var_use;
296
297 if (SS.isSet())
298 Diag(IdLoc, DiagID) << &II << SS.getRange();
299 else
300 Diag(IdLoc, DiagID) << &II;
301
302 return 0;
303}
304
Douglas Gregor39a8de12009-02-25 19:37:18 +0000305Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
306 const CXXScopeSpec &SS,
307 TypeTy *Ty,
308 SourceRange TypeRange,
309 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000310 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000311 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000312 QualType T = QualType::getFromOpaquePtr(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000313 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000314 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000315}
316
Cedric Venet3d658642009-02-14 20:20:19 +0000317/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
318/// scope or nested-name-specifier) is parsed, part of a declarator-id.
319/// After this method is called, according to [C++ 3.4.3p3], names should be
320/// looked up in the declarator-id's scope, until the declarator is parsed and
321/// ActOnCXXExitDeclaratorScope is called.
322/// The 'SS' should be a non-empty valid CXXScopeSpec.
323void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
324 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000325 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000326 EnterDeclaratorContext(S, DC);
327 else
328 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cedric Venet3d658642009-02-14 20:20:19 +0000329}
330
331/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
332/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
333/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
334/// Used to indicate that names should revert to being looked up in the
335/// defining scope.
336void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
337 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000338 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000339 "Context imbalance!");
340 if (!SS.isInvalid())
341 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000342}