blob: 1580e721d35981e4e98489fe0622e20e5ab228b6 [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"
Douglas Gregor7551c182009-07-22 00:28:09 +000020#include "llvm/Support/raw_ostream.h"
Cedric Venet3d658642009-02-14 20:20:19 +000021using namespace clang;
22
Douglas Gregore4e5b052009-03-19 00:18:19 +000023/// \brief Compute the DeclContext that is associated with the given
24/// scope specifier.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000025///
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) {
Douglas Gregore4e5b052009-03-19 00:18:19 +000038 if (!SS.isSet() || SS.isInvalid())
Douglas Gregorca5e77f2009-03-18 00:36:05 +000039 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +000040
Douglas Gregorab452ba2009-03-26 23:50:42 +000041 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +000042 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor42af25f2009-05-11 19:58:34 +000043 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;
Douglas Gregorf59a56e2009-07-21 23:53:31 +000048
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
Douglas Gregor7551c182009-07-22 00:28:09 +000052 // or a class template partial specialization.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000053 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())) {
Douglas Gregorb88e8882009-07-30 17:40:51 +000058 QualType ContextType
59 = Context.getCanonicalType(QualType(SpecType, 0));
60
Douglas Gregorf59a56e2009-07-21 23:53:31 +000061 // 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);
Douglas Gregorb88e8882009-07-30 17:40:51 +000065 if (Context.hasSameType(Injected, ContextType))
Douglas Gregorf59a56e2009-07-21 23:53:31 +000066 return ClassTemplate->getTemplatedDecl();
67
Douglas Gregorb88e8882009-07-30 17:40:51 +000068 // 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;
Douglas Gregorf59a56e2009-07-21 23:53:31 +000075 }
76 }
Douglas Gregor7551c182009-07-22 00:28:09 +000077
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();
Douglas Gregorf59a56e2009-07-21 23:53:31 +000088 }
89
90 return 0;
Douglas Gregor42af25f2009-05-11 19:58:34 +000091 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000092
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: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000103 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
Douglas Gregorab452ba2009-03-26 23:50:42 +0000104 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;
Douglas Gregorca5e77f2009-03-18 00:36:05 +0000114}
115
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000116bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
117 if (!SS.isSet() || SS.isInvalid())
118 return false;
119
Douglas Gregorab452ba2009-03-26 23:50:42 +0000120 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +0000121 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000122 return NNS->isDependent();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000123}
124
Douglas Gregor42af25f2009-05-11 19:58:34 +0000125// \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.
128bool 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.
142CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
143 assert(getLangOptions().CPlusPlus && "Only callable in C++");
144 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
145
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000146 if (!NNS->getAsType())
147 return 0;
148
149 QualType T = Context.getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor42af25f2009-05-11 19:58:34 +0000150 // 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. (FIXME)
193 //
194 // All of these options come down to having the
195 // nested-name-specifier type that is equivalent to the
196 // injected-class-name of one of the types that is currently in
197 // our context.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000198 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000199 return Record;
200
201 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
202 QualType InjectedClassName
203 = Template->getInjectedClassNameType(Context);
204 if (T == Context.getCanonicalType(InjectedClassName))
205 return Template->getTemplatedDecl();
206 }
Douglas Gregorb88e8882009-07-30 17:40:51 +0000207 // FIXME: check for class template partial specializations
Douglas Gregor42af25f2009-05-11 19:58:34 +0000208 }
209
210 return 0;
211}
212
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000213/// \brief Require that the context specified by SS be complete.
214///
215/// If SS refers to a type, this routine checks whether the type is
216/// complete enough (or can be made complete enough) for name lookup
217/// into the DeclContext. A type that is not yet completed can be
218/// considered "complete enough" if it is a class/struct/union/enum
219/// that is currently being defined. Or, if we have a type that names
220/// a class template specialization that is not a complete type, we
221/// will attempt to instantiate that class template.
222bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
223 if (!SS.isSet() || SS.isInvalid())
224 return false;
225
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000226 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000227 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
228 // If we're currently defining this type, then lookup into the
229 // type is okay: don't complain that it isn't complete yet.
Ted Kremenek6217b802009-07-29 21:53:49 +0000230 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000231 if (TagT->isBeingDefined())
232 return false;
233
234 // The type must be complete.
235 return RequireCompleteType(SS.getRange().getBegin(),
236 Context.getTypeDeclType(Tag),
237 diag::err_incomplete_nested_name_spec,
238 SS.getRange());
239 }
240
241 return false;
242}
Cedric Venet3d658642009-02-14 20:20:19 +0000243
244/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
245/// global scope ('::').
246Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
247 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000248 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000249}
250
251/// ActOnCXXNestedNameSpecifier - Called during parsing of a
252/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
253/// we want to resolve "bar::". 'SS' is empty or the previously parsed
254/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
255/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
256/// Returns a CXXScopeTy* object representing the C++ scope.
257Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
258 const CXXScopeSpec &SS,
259 SourceLocation IdLoc,
260 SourceLocation CCLoc,
261 IdentifierInfo &II) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000262 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000263 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000264
Douglas Gregor42af25f2009-05-11 19:58:34 +0000265 // If the prefix already refers to an unknown specialization, there
266 // is no name lookup to perform. Just build the resulting
267 // nested-name-specifier.
268 if (Prefix && isUnknownSpecialization(SS))
Douglas Gregorab452ba2009-03-26 23:50:42 +0000269 return NestedNameSpecifier::Create(Context, Prefix, &II);
270
Cedric Venet3d658642009-02-14 20:20:19 +0000271 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
272
273 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000274 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
275 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000276
Douglas Gregorab452ba2009-03-26 23:50:42 +0000277 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
278 // Determine whether we have a class (or, in C++0x, an enum) or
279 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord57959a2009-03-27 23:10:48 +0000280 QualType T = Context.getTypeDeclType(Type);
281 bool AcceptableType = false;
282 if (T->isDependentType())
283 AcceptableType = true;
284 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000285 if (TD->getUnderlyingType()->isRecordType() ||
286 (getLangOptions().CPlusPlus0x &&
287 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000288 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000289 } else if (isa<RecordDecl>(Type) ||
290 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000291 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000292
Douglas Gregord57959a2009-03-27 23:10:48 +0000293 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000294 return NestedNameSpecifier::Create(Context, Prefix, false,
295 T.getTypePtr());
296 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000297
298 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
299 return NestedNameSpecifier::Create(Context, Prefix,
300 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000301
302 // Fall through to produce an error: we found something that isn't
303 // a class or a namespace.
304 }
305
306 // If we didn't find anything during our lookup, try again with
307 // ordinary name lookup, which can help us produce better error
308 // messages.
309 if (!SD)
310 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName);
311 unsigned DiagID;
312 if (SD)
313 DiagID = diag::err_expected_class_or_namespace;
314 else if (SS.isSet())
315 DiagID = diag::err_typecheck_no_member;
316 else
317 DiagID = diag::err_undeclared_var_use;
318
319 if (SS.isSet())
320 Diag(IdLoc, DiagID) << &II << SS.getRange();
321 else
322 Diag(IdLoc, DiagID) << &II;
323
324 return 0;
325}
326
Douglas Gregor39a8de12009-02-25 19:37:18 +0000327Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
328 const CXXScopeSpec &SS,
329 TypeTy *Ty,
330 SourceRange TypeRange,
331 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000332 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000333 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000334 QualType T = QualType::getFromOpaquePtr(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000335 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000336 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000337}
338
Cedric Venet3d658642009-02-14 20:20:19 +0000339/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
340/// scope or nested-name-specifier) is parsed, part of a declarator-id.
341/// After this method is called, according to [C++ 3.4.3p3], names should be
342/// looked up in the declarator-id's scope, until the declarator is parsed and
343/// ActOnCXXExitDeclaratorScope is called.
344/// The 'SS' should be a non-empty valid CXXScopeSpec.
345void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
346 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000347 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000348 EnterDeclaratorContext(S, DC);
349 else
350 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cedric Venet3d658642009-02-14 20:20:19 +0000351}
352
353/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
354/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
355/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
356/// Used to indicate that names should revert to being looked up in the
357/// defining scope.
358void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
359 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000360 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000361 "Context imbalance!");
362 if (!SS.isInvalid())
363 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000364}