blob: 2d89cfa07266a3b18abecf317cd75bb18d503c72 [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 Gregorfe85ced2009-08-06 03:17:00 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregore4e5b052009-03-19 00:18:19 +000018#include "clang/AST/NestedNameSpecifier.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Cedric Venet3d658642009-02-14 20:20:19 +000020#include "clang/Parse/DeclSpec.h"
21#include "llvm/ADT/STLExtras.h"
Douglas Gregor7551c182009-07-22 00:28:09 +000022#include "llvm/Support/raw_ostream.h"
Cedric Venet3d658642009-02-14 20:20:19 +000023using namespace clang;
24
Douglas Gregore4e5b052009-03-19 00:18:19 +000025/// \brief Compute the DeclContext that is associated with the given
26/// scope specifier.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000027///
28/// \param SS the C++ scope specifier as it appears in the source
29///
30/// \param EnteringContext when true, we will be entering the context of
31/// this scope specifier, so we can retrieve the declaration context of a
32/// class template or class template partial specialization even if it is
33/// not the current instantiation.
34///
35/// \returns the declaration context represented by the scope specifier @p SS,
36/// or NULL if the declaration context cannot be computed (e.g., because it is
37/// dependent and not the current instantiation).
38DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
39 bool EnteringContext) {
Douglas Gregore4e5b052009-03-19 00:18:19 +000040 if (!SS.isSet() || SS.isInvalid())
Douglas Gregorca5e77f2009-03-18 00:36:05 +000041 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +000042
Douglas Gregorab452ba2009-03-26 23:50:42 +000043 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +000044 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor42af25f2009-05-11 19:58:34 +000045 if (NNS->isDependent()) {
46 // If this nested-name-specifier refers to the current
47 // instantiation, return its DeclContext.
48 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
49 return Record;
Douglas Gregorf59a56e2009-07-21 23:53:31 +000050
51 if (EnteringContext) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +000052 if (const TemplateSpecializationType *SpecType
53 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
Douglas Gregor495c35d2009-08-25 22:51:20 +000054 // We are entering the context of the nested name specifier, so try to
55 // match the nested name specifier to either a primary class template
56 // or a class template partial specialization.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000057 if (ClassTemplateDecl *ClassTemplate
58 = dyn_cast_or_null<ClassTemplateDecl>(
59 SpecType->getTemplateName().getAsTemplateDecl())) {
Douglas Gregorb88e8882009-07-30 17:40:51 +000060 QualType ContextType
61 = Context.getCanonicalType(QualType(SpecType, 0));
62
Douglas Gregorf59a56e2009-07-21 23:53:31 +000063 // If the type of the nested name specifier is the same as the
64 // injected class name of the named class template, we're entering
65 // into that class template definition.
66 QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
Douglas Gregorb88e8882009-07-30 17:40:51 +000067 if (Context.hasSameType(Injected, ContextType))
Douglas Gregorf59a56e2009-07-21 23:53:31 +000068 return ClassTemplate->getTemplatedDecl();
69
Douglas Gregorb88e8882009-07-30 17:40:51 +000070 // If the type of the nested name specifier is the same as the
71 // type of one of the class template's class template partial
72 // specializations, we're entering into the definition of that
73 // class template partial specialization.
74 if (ClassTemplatePartialSpecializationDecl *PartialSpec
75 = ClassTemplate->findPartialSpecialization(ContextType))
76 return PartialSpec;
Douglas Gregorf59a56e2009-07-21 23:53:31 +000077 }
Douglas Gregor495c35d2009-08-25 22:51:20 +000078 } else if (const RecordType *RecordT
79 = dyn_cast_or_null<RecordType>(NNS->getAsType())) {
80 // The nested name specifier refers to a member of a class template.
81 return RecordT->getDecl();
Douglas Gregorf59a56e2009-07-21 23:53:31 +000082 }
83 }
84
85 return 0;
Douglas Gregor42af25f2009-05-11 19:58:34 +000086 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000087
88 switch (NNS->getKind()) {
89 case NestedNameSpecifier::Identifier:
90 assert(false && "Dependent nested-name-specifier has no DeclContext");
91 break;
92
93 case NestedNameSpecifier::Namespace:
94 return NNS->getAsNamespace();
95
96 case NestedNameSpecifier::TypeSpec:
97 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenek6217b802009-07-29 21:53:49 +000098 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
Douglas Gregorab452ba2009-03-26 23:50:42 +000099 assert(Tag && "Non-tag type in nested-name-specifier");
100 return Tag->getDecl();
101 } break;
102
103 case NestedNameSpecifier::Global:
104 return Context.getTranslationUnitDecl();
105 }
106
107 // Required to silence a GCC warning.
108 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +0000109}
110
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000111bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
112 if (!SS.isSet() || SS.isInvalid())
113 return false;
114
Douglas Gregorab452ba2009-03-26 23:50:42 +0000115 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +0000116 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000117 return NNS->isDependent();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000118}
119
Douglas Gregor42af25f2009-05-11 19:58:34 +0000120// \brief Determine whether this C++ scope specifier refers to an
121// unknown specialization, i.e., a dependent type that is not the
122// current instantiation.
123bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
124 if (!isDependentScopeSpecifier(SS))
125 return false;
126
127 NestedNameSpecifier *NNS
128 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
129 return getCurrentInstantiationOf(NNS) == 0;
130}
131
132/// \brief If the given nested name specifier refers to the current
133/// instantiation, return the declaration that corresponds to that
134/// current instantiation (C++0x [temp.dep.type]p1).
135///
136/// \param NNS a dependent nested name specifier.
137CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
138 assert(getLangOptions().CPlusPlus && "Only callable in C++");
139 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
140
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000141 if (!NNS->getAsType())
142 return 0;
143
Douglas Gregor1560def2009-07-31 18:32:42 +0000144 QualType T = QualType(NNS->getAsType(), 0);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000145 // If the nested name specifier does not refer to a type, then it
146 // does not refer to the current instantiation.
147 if (T.isNull())
148 return 0;
149
150 T = Context.getCanonicalType(T);
151
152 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
153 // If we've hit a namespace or the global scope, then the
154 // nested-name-specifier can't refer to the current instantiation.
155 if (Ctx->isFileContext())
156 return 0;
157
158 // Skip non-class contexts.
159 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
160 if (!Record)
161 continue;
162
163 // If this record type is not dependent,
164 if (!Record->isDependentType())
165 return 0;
166
167 // C++ [temp.dep.type]p1:
168 //
169 // In the definition of a class template, a nested class of a
170 // class template, a member of a class template, or a member of a
171 // nested class of a class template, a name refers to the current
172 // instantiation if it is
173 // -- the injected-class-name (9) of the class template or
174 // nested class,
175 // -- in the definition of a primary class template, the name
176 // of the class template followed by the template argument
177 // list of the primary template (as described below)
178 // enclosed in <>,
179 // -- in the definition of a nested class of a class template,
180 // the name of the nested class referenced as a member of
181 // the current instantiation, or
182 // -- in the definition of a partial specialization, the name
183 // of the class template followed by the template argument
184 // list of the partial specialization enclosed in <>. If
185 // the nth template parameter is a parameter pack, the nth
186 // template argument is a pack expansion (14.6.3) whose
Douglas Gregorc5b8c9b2009-07-30 17:50:56 +0000187 // pattern is the name of the parameter pack.
188 // (FIXME: parameter packs)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000189 //
190 // All of these options come down to having the
191 // nested-name-specifier type that is equivalent to the
192 // injected-class-name of one of the types that is currently in
193 // our context.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000194 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000195 return Record;
196
197 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
198 QualType InjectedClassName
199 = Template->getInjectedClassNameType(Context);
200 if (T == Context.getCanonicalType(InjectedClassName))
201 return Template->getTemplatedDecl();
202 }
Douglas Gregorb88e8882009-07-30 17:40:51 +0000203 // FIXME: check for class template partial specializations
Douglas Gregor42af25f2009-05-11 19:58:34 +0000204 }
205
206 return 0;
207}
208
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000209/// \brief Require that the context specified by SS be complete.
210///
211/// If SS refers to a type, this routine checks whether the type is
212/// complete enough (or can be made complete enough) for name lookup
213/// into the DeclContext. A type that is not yet completed can be
214/// considered "complete enough" if it is a class/struct/union/enum
215/// that is currently being defined. Or, if we have a type that names
216/// a class template specialization that is not a complete type, we
217/// will attempt to instantiate that class template.
218bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
219 if (!SS.isSet() || SS.isInvalid())
220 return false;
221
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000222 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000223 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
224 // If we're currently defining this type, then lookup into the
225 // type is okay: don't complain that it isn't complete yet.
Ted Kremenek6217b802009-07-29 21:53:49 +0000226 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000227 if (TagT->isBeingDefined())
228 return false;
229
230 // The type must be complete.
231 return RequireCompleteType(SS.getRange().getBegin(),
232 Context.getTypeDeclType(Tag),
Anders Carlssonb7906612009-08-26 23:45:07 +0000233 PDiag(diag::err_incomplete_nested_name_spec)
234 << SS.getRange());
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000235 }
236
237 return false;
238}
Cedric Venet3d658642009-02-14 20:20:19 +0000239
240/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
241/// global scope ('::').
242Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
243 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000244 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000245}
246
247/// ActOnCXXNestedNameSpecifier - Called during parsing of a
248/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
249/// we want to resolve "bar::". 'SS' is empty or the previously parsed
250/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
251/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
252/// Returns a CXXScopeTy* object representing the C++ scope.
253Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
254 const CXXScopeSpec &SS,
255 SourceLocation IdLoc,
256 SourceLocation CCLoc,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000257 IdentifierInfo &II,
258 bool EnteringContext) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000259 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000260 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000261
Douglas Gregor495c35d2009-08-25 22:51:20 +0000262 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName,
263 false, false, SourceLocation(),
264 EnteringContext);
Cedric Venet3d658642009-02-14 20:20:19 +0000265
266 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000267 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
268 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000269
Douglas Gregorab452ba2009-03-26 23:50:42 +0000270 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
271 // Determine whether we have a class (or, in C++0x, an enum) or
272 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord57959a2009-03-27 23:10:48 +0000273 QualType T = Context.getTypeDeclType(Type);
274 bool AcceptableType = false;
275 if (T->isDependentType())
276 AcceptableType = true;
277 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000278 if (TD->getUnderlyingType()->isRecordType() ||
279 (getLangOptions().CPlusPlus0x &&
280 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000281 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000282 } else if (isa<RecordDecl>(Type) ||
283 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000284 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000285
Douglas Gregord57959a2009-03-27 23:10:48 +0000286 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000287 return NestedNameSpecifier::Create(Context, Prefix, false,
288 T.getTypePtr());
289 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000290
Douglas Gregordacd4342009-08-26 00:04:55 +0000291 // FIXME: It would be nice to maintain the namespace alias name, then
292 // see through that alias when resolving the nested-name-specifier down to
293 // a declaration context.
Anders Carlsson81c85c42009-03-28 23:53:49 +0000294 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
295 return NestedNameSpecifier::Create(Context, Prefix,
296 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000297
298 // Fall through to produce an error: we found something that isn't
299 // a class or a namespace.
Douglas Gregor495c35d2009-08-25 22:51:20 +0000300 } else if (SS.isSet() && isDependentScopeSpecifier(SS))
301 return NestedNameSpecifier::Create(Context, Prefix, &II);
Cedric Venet3d658642009-02-14 20:20:19 +0000302
303 // If we didn't find anything during our lookup, try again with
304 // ordinary name lookup, which can help us produce better error
305 // messages.
306 if (!SD)
Douglas Gregor495c35d2009-08-25 22:51:20 +0000307 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName,
308 false, false, SourceLocation(),
309 EnteringContext);
Cedric Venet3d658642009-02-14 20:20:19 +0000310 unsigned DiagID;
311 if (SD)
312 DiagID = diag::err_expected_class_or_namespace;
313 else if (SS.isSet())
314 DiagID = diag::err_typecheck_no_member;
315 else
316 DiagID = diag::err_undeclared_var_use;
317
318 if (SS.isSet())
319 Diag(IdLoc, DiagID) << &II << SS.getRange();
320 else
321 Diag(IdLoc, DiagID) << &II;
322
323 return 0;
324}
325
Douglas Gregor39a8de12009-02-25 19:37:18 +0000326Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
327 const CXXScopeSpec &SS,
328 TypeTy *Ty,
329 SourceRange TypeRange,
330 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000331 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000332 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000333 QualType T = GetTypeFromParser(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000334 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000335 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000336}
337
Douglas Gregorfe85ced2009-08-06 03:17:00 +0000338Action::OwningExprResult
339Sema::ActOnCXXEnterMemberScope(Scope *S, CXXScopeSpec &SS, ExprArg Base,
340 tok::TokenKind OpKind) {
Nate Begeman2ef13e52009-08-10 23:49:36 +0000341 // Since this might be a postfix expression, get rid of ParenListExprs.
342 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
343
Douglas Gregorfe85ced2009-08-06 03:17:00 +0000344 Expr *BaseExpr = (Expr*)Base.get();
345 assert(BaseExpr && "no record expansion");
346
347 QualType BaseType = BaseExpr->getType();
348 // FIXME: handle dependent types
349 if (BaseType->isDependentType())
350 return move(Base);
351
352 // C++ [over.match.oper]p8:
353 // [...] When operator->returns, the operator-> is applied to the value
354 // returned, with the original second operand.
355 if (OpKind == tok::arrow) {
356 while (BaseType->isRecordType()) {
357 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
358 BaseExpr = (Expr*)Base.get();
359 if (BaseExpr == NULL)
360 return ExprError();
361 BaseType = BaseExpr->getType();
362 }
363 }
364
365 if (BaseType->isPointerType())
366 BaseType = BaseType->getPointeeType();
367
368 // We could end up with various non-record types here, such as extended
369 // vector types or Objective-C interfaces. Just return early and let
370 // ActOnMemberReferenceExpr do the work.
371 if (!BaseType->isRecordType())
372 return move(Base);
373
374 SS.setRange(BaseExpr->getSourceRange());
375 SS.setScopeRep(
376 NestedNameSpecifier::Create(Context, 0, false, BaseType.getTypePtr())
377 );
378
379 if (S)
380 ActOnCXXEnterDeclaratorScope(S,SS);
381 return move(Base);
382}
383
384void Sema::ActOnCXXExitMemberScope(Scope *S, const CXXScopeSpec &SS) {
385 if (S && SS.isSet())
386 ActOnCXXExitDeclaratorScope(S,SS);
387}
388
389
Cedric Venet3d658642009-02-14 20:20:19 +0000390/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
391/// scope or nested-name-specifier) is parsed, part of a declarator-id.
392/// After this method is called, according to [C++ 3.4.3p3], names should be
393/// looked up in the declarator-id's scope, until the declarator is parsed and
394/// ActOnCXXExitDeclaratorScope is called.
395/// The 'SS' should be a non-empty valid CXXScopeSpec.
396void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
397 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000398 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000399 EnterDeclaratorContext(S, DC);
Cedric Venet3d658642009-02-14 20:20:19 +0000400}
401
402/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
403/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
404/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
405/// Used to indicate that names should revert to being looked up in the
406/// defining scope.
407void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
408 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregordacd4342009-08-26 00:04:55 +0000409 if (SS.isInvalid())
410 return;
411 if (computeDeclContext(SS, true))
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000412 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000413}