blob: 27e0ccf7d5bec4566bee5f32d90a833880da0bb0 [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
Douglas Gregor1560def2009-07-31 18:32:42 +0000149 QualType T = 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
Douglas Gregorc5b8c9b2009-07-30 17:50:56 +0000192 // pattern is the name of the parameter pack.
193 // (FIXME: parameter packs)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000194 //
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.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000199 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000200 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 }
Douglas Gregorb88e8882009-07-30 17:40:51 +0000208 // FIXME: check for class template partial specializations
Douglas Gregor42af25f2009-05-11 19:58:34 +0000209 }
210
211 return 0;
212}
213
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000214/// \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.
223bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
224 if (!SS.isSet() || SS.isInvalid())
225 return false;
226
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000227 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000228 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.
Ted Kremenek6217b802009-07-29 21:53:49 +0000231 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000232 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}
Cedric Venet3d658642009-02-14 20:20:19 +0000244
245/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
246/// global scope ('::').
247Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
248 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000249 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000250}
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.
258Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
259 const CXXScopeSpec &SS,
260 SourceLocation IdLoc,
261 SourceLocation CCLoc,
262 IdentifierInfo &II) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000263 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000264 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000265
Douglas Gregor42af25f2009-05-11 19:58:34 +0000266 // 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))
Douglas Gregorab452ba2009-03-26 23:50:42 +0000270 return NestedNameSpecifier::Create(Context, Prefix, &II);
271
Cedric Venet3d658642009-02-14 20:20:19 +0000272 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
273
274 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000275 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
276 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000277
Douglas Gregorab452ba2009-03-26 23:50:42 +0000278 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.
Douglas Gregord57959a2009-03-27 23:10:48 +0000281 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)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000286 if (TD->getUnderlyingType()->isRecordType() ||
287 (getLangOptions().CPlusPlus0x &&
288 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000289 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000290 } else if (isa<RecordDecl>(Type) ||
291 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000292 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000293
Douglas Gregord57959a2009-03-27 23:10:48 +0000294 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000295 return NestedNameSpecifier::Create(Context, Prefix, false,
296 T.getTypePtr());
297 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000298
299 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
300 return NestedNameSpecifier::Create(Context, Prefix,
301 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000302
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
Douglas Gregor39a8de12009-02-25 19:37:18 +0000328Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
329 const CXXScopeSpec &SS,
330 TypeTy *Ty,
331 SourceRange TypeRange,
332 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000333 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000334 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000335 QualType T = QualType::getFromOpaquePtr(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000336 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000337 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000338}
339
Cedric Venet3d658642009-02-14 20:20:19 +0000340/// 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.
346void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
347 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000348 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000349 EnterDeclaratorContext(S, DC);
350 else
351 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cedric Venet3d658642009-02-14 20:20:19 +0000352}
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.
359void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
360 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000361 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000362 "Context imbalance!");
363 if (!SS.isInvalid())
364 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000365}