blob: cf73725e7f36536579d6604feed19114d188160b [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())) {
58 // If the type of the nested name specifier is the same as the
59 // injected class name of the named class template, we're entering
60 // into that class template definition.
61 QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
62 if (Context.hasSameType(Injected, QualType(SpecType, 0)))
63 return ClassTemplate->getTemplatedDecl();
64
65 // FIXME: Class template partial specializations
66 }
67 }
Douglas Gregor7551c182009-07-22 00:28:09 +000068
69 std::string NNSString;
70 {
71 llvm::raw_string_ostream OS(NNSString);
72 NNS->print(OS, Context.PrintingPolicy);
73 }
74
75 // FIXME: Allow us to pass a nested-name-specifier to Diag?
76 Diag(SS.getRange().getBegin(),
77 diag::err_template_qualified_declarator_no_match)
78 << NNSString << SS.getRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +000079 }
80
81 return 0;
Douglas Gregor42af25f2009-05-11 19:58:34 +000082 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000083
84 switch (NNS->getKind()) {
85 case NestedNameSpecifier::Identifier:
86 assert(false && "Dependent nested-name-specifier has no DeclContext");
87 break;
88
89 case NestedNameSpecifier::Namespace:
90 return NNS->getAsNamespace();
91
92 case NestedNameSpecifier::TypeSpec:
93 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenek35366a62009-07-17 17:50:17 +000094 const TagType *Tag = NNS->getAsType()->getAsTagType();
Douglas Gregorab452ba2009-03-26 23:50:42 +000095 assert(Tag && "Non-tag type in nested-name-specifier");
96 return Tag->getDecl();
97 } break;
98
99 case NestedNameSpecifier::Global:
100 return Context.getTranslationUnitDecl();
101 }
102
103 // Required to silence a GCC warning.
104 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +0000105}
106
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000107bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
108 if (!SS.isSet() || SS.isInvalid())
109 return false;
110
Douglas Gregorab452ba2009-03-26 23:50:42 +0000111 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +0000112 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000113 return NNS->isDependent();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000114}
115
Douglas Gregor42af25f2009-05-11 19:58:34 +0000116// \brief Determine whether this C++ scope specifier refers to an
117// unknown specialization, i.e., a dependent type that is not the
118// current instantiation.
119bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
120 if (!isDependentScopeSpecifier(SS))
121 return false;
122
123 NestedNameSpecifier *NNS
124 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
125 return getCurrentInstantiationOf(NNS) == 0;
126}
127
128/// \brief If the given nested name specifier refers to the current
129/// instantiation, return the declaration that corresponds to that
130/// current instantiation (C++0x [temp.dep.type]p1).
131///
132/// \param NNS a dependent nested name specifier.
133CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
134 assert(getLangOptions().CPlusPlus && "Only callable in C++");
135 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
136
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000137 if (!NNS->getAsType())
138 return 0;
139
140 QualType T = Context.getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor42af25f2009-05-11 19:58:34 +0000141 // If the nested name specifier does not refer to a type, then it
142 // does not refer to the current instantiation.
143 if (T.isNull())
144 return 0;
145
146 T = Context.getCanonicalType(T);
147
148 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
149 // If we've hit a namespace or the global scope, then the
150 // nested-name-specifier can't refer to the current instantiation.
151 if (Ctx->isFileContext())
152 return 0;
153
154 // Skip non-class contexts.
155 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
156 if (!Record)
157 continue;
158
159 // If this record type is not dependent,
160 if (!Record->isDependentType())
161 return 0;
162
163 // C++ [temp.dep.type]p1:
164 //
165 // In the definition of a class template, a nested class of a
166 // class template, a member of a class template, or a member of a
167 // nested class of a class template, a name refers to the current
168 // instantiation if it is
169 // -- the injected-class-name (9) of the class template or
170 // nested class,
171 // -- in the definition of a primary class template, the name
172 // of the class template followed by the template argument
173 // list of the primary template (as described below)
174 // enclosed in <>,
175 // -- in the definition of a nested class of a class template,
176 // the name of the nested class referenced as a member of
177 // the current instantiation, or
178 // -- in the definition of a partial specialization, the name
179 // of the class template followed by the template argument
180 // list of the partial specialization enclosed in <>. If
181 // the nth template parameter is a parameter pack, the nth
182 // template argument is a pack expansion (14.6.3) whose
183 // pattern is the name of the parameter pack. (FIXME)
184 //
185 // All of these options come down to having the
186 // nested-name-specifier type that is equivalent to the
187 // injected-class-name of one of the types that is currently in
188 // our context.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000189 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000190 return Record;
191
192 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
193 QualType InjectedClassName
194 = Template->getInjectedClassNameType(Context);
195 if (T == Context.getCanonicalType(InjectedClassName))
196 return Template->getTemplatedDecl();
197 }
198 }
199
200 return 0;
201}
202
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000203/// \brief Require that the context specified by SS be complete.
204///
205/// If SS refers to a type, this routine checks whether the type is
206/// complete enough (or can be made complete enough) for name lookup
207/// into the DeclContext. A type that is not yet completed can be
208/// considered "complete enough" if it is a class/struct/union/enum
209/// that is currently being defined. Or, if we have a type that names
210/// a class template specialization that is not a complete type, we
211/// will attempt to instantiate that class template.
212bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
213 if (!SS.isSet() || SS.isInvalid())
214 return false;
215
Douglas Gregore4e5b052009-03-19 00:18:19 +0000216 DeclContext *DC = computeDeclContext(SS);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000217 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
218 // If we're currently defining this type, then lookup into the
219 // type is okay: don't complain that it isn't complete yet.
Ted Kremenek35366a62009-07-17 17:50:17 +0000220 const TagType *TagT = Context.getTypeDeclType(Tag)->getAsTagType();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000221 if (TagT->isBeingDefined())
222 return false;
223
224 // The type must be complete.
225 return RequireCompleteType(SS.getRange().getBegin(),
226 Context.getTypeDeclType(Tag),
227 diag::err_incomplete_nested_name_spec,
228 SS.getRange());
229 }
230
231 return false;
232}
Cedric Venet3d658642009-02-14 20:20:19 +0000233
234/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
235/// global scope ('::').
236Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
237 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000238 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000239}
240
241/// ActOnCXXNestedNameSpecifier - Called during parsing of a
242/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
243/// we want to resolve "bar::". 'SS' is empty or the previously parsed
244/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
245/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
246/// Returns a CXXScopeTy* object representing the C++ scope.
247Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
248 const CXXScopeSpec &SS,
249 SourceLocation IdLoc,
250 SourceLocation CCLoc,
251 IdentifierInfo &II) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000252 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000253 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000254
Douglas Gregor42af25f2009-05-11 19:58:34 +0000255 // If the prefix already refers to an unknown specialization, there
256 // is no name lookup to perform. Just build the resulting
257 // nested-name-specifier.
258 if (Prefix && isUnknownSpecialization(SS))
Douglas Gregorab452ba2009-03-26 23:50:42 +0000259 return NestedNameSpecifier::Create(Context, Prefix, &II);
260
Cedric Venet3d658642009-02-14 20:20:19 +0000261 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
262
263 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000264 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
265 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000266
Douglas Gregorab452ba2009-03-26 23:50:42 +0000267 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
268 // Determine whether we have a class (or, in C++0x, an enum) or
269 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord57959a2009-03-27 23:10:48 +0000270 QualType T = Context.getTypeDeclType(Type);
271 bool AcceptableType = false;
272 if (T->isDependentType())
273 AcceptableType = true;
274 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000275 if (TD->getUnderlyingType()->isRecordType() ||
276 (getLangOptions().CPlusPlus0x &&
277 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000278 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000279 } else if (isa<RecordDecl>(Type) ||
280 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000281 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000282
Douglas Gregord57959a2009-03-27 23:10:48 +0000283 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000284 return NestedNameSpecifier::Create(Context, Prefix, false,
285 T.getTypePtr());
286 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000287
288 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
289 return NestedNameSpecifier::Create(Context, Prefix,
290 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000291
292 // Fall through to produce an error: we found something that isn't
293 // a class or a namespace.
294 }
295
296 // If we didn't find anything during our lookup, try again with
297 // ordinary name lookup, which can help us produce better error
298 // messages.
299 if (!SD)
300 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName);
301 unsigned DiagID;
302 if (SD)
303 DiagID = diag::err_expected_class_or_namespace;
304 else if (SS.isSet())
305 DiagID = diag::err_typecheck_no_member;
306 else
307 DiagID = diag::err_undeclared_var_use;
308
309 if (SS.isSet())
310 Diag(IdLoc, DiagID) << &II << SS.getRange();
311 else
312 Diag(IdLoc, DiagID) << &II;
313
314 return 0;
315}
316
Douglas Gregor39a8de12009-02-25 19:37:18 +0000317Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
318 const CXXScopeSpec &SS,
319 TypeTy *Ty,
320 SourceRange TypeRange,
321 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000322 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000323 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000324 QualType T = QualType::getFromOpaquePtr(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000325 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000326 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000327}
328
Cedric Venet3d658642009-02-14 20:20:19 +0000329/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
330/// scope or nested-name-specifier) is parsed, part of a declarator-id.
331/// After this method is called, according to [C++ 3.4.3p3], names should be
332/// looked up in the declarator-id's scope, until the declarator is parsed and
333/// ActOnCXXExitDeclaratorScope is called.
334/// The 'SS' should be a non-empty valid CXXScopeSpec.
335void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
336 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000337 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000338 EnterDeclaratorContext(S, DC);
339 else
340 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cedric Venet3d658642009-02-14 20:20:19 +0000341}
342
343/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
344/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
345/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
346/// Used to indicate that names should revert to being looked up in the
347/// defining scope.
348void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
349 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000350 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000351 "Context imbalance!");
352 if (!SS.isInvalid())
353 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000354}