blob: 3dac5d7297b167d387b74f7629e58af25e966bcd [file] [log] [blame]
Cédric Venet31c94022009-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 Gregor3eb20702009-05-11 19:58:34 +000016#include "clang/AST/DeclTemplate.h"
Douglas Gregorda61ad22009-08-06 03:17:00 +000017#include "clang/AST/ExprCXX.h"
Douglas Gregor734b4ba2009-03-19 00:18:19 +000018#include "clang/AST/NestedNameSpecifier.h"
Cédric Venet31c94022009-02-14 20:20:19 +000019#include "clang/Parse/DeclSpec.h"
20#include "llvm/ADT/STLExtras.h"
Douglas Gregor179bcef2009-07-22 00:28:09 +000021#include "llvm/Support/raw_ostream.h"
Cédric Venet31c94022009-02-14 20:20:19 +000022using namespace clang;
23
Douglas Gregor734b4ba2009-03-19 00:18:19 +000024/// \brief Compute the DeclContext that is associated with the given
25/// scope specifier.
Douglas Gregorb462c322009-07-21 23:53:31 +000026///
27/// \param SS the C++ scope specifier as it appears in the source
28///
29/// \param EnteringContext when true, we will be entering the context of
30/// this scope specifier, so we can retrieve the declaration context of a
31/// class template or class template partial specialization even if it is
32/// not the current instantiation.
33///
34/// \returns the declaration context represented by the scope specifier @p SS,
35/// or NULL if the declaration context cannot be computed (e.g., because it is
36/// dependent and not the current instantiation).
37DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
38 bool EnteringContext) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +000039 if (!SS.isSet() || SS.isInvalid())
Douglas Gregor253fc4d2009-03-18 00:36:05 +000040 return 0;
Douglas Gregor253fc4d2009-03-18 00:36:05 +000041
Douglas Gregor1e589cc2009-03-26 23:50:42 +000042 NestedNameSpecifier *NNS
Douglas Gregor041e9292009-03-26 23:56:24 +000043 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3eb20702009-05-11 19:58:34 +000044 if (NNS->isDependent()) {
45 // If this nested-name-specifier refers to the current
46 // instantiation, return its DeclContext.
47 if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
48 return Record;
Douglas Gregorb462c322009-07-21 23:53:31 +000049
50 if (EnteringContext) {
Douglas Gregorb462c322009-07-21 23:53:31 +000051 if (const TemplateSpecializationType *SpecType
52 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
Douglas Gregorc03d3302009-08-25 22:51:20 +000053 // We are entering the context of the nested name specifier, so try to
54 // match the nested name specifier to either a primary class template
55 // or a class template partial specialization.
Douglas Gregorb462c322009-07-21 23:53:31 +000056 if (ClassTemplateDecl *ClassTemplate
57 = dyn_cast_or_null<ClassTemplateDecl>(
58 SpecType->getTemplateName().getAsTemplateDecl())) {
Douglas Gregor1930d202009-07-30 17:40:51 +000059 QualType ContextType
60 = Context.getCanonicalType(QualType(SpecType, 0));
61
Douglas Gregorb462c322009-07-21 23:53:31 +000062 // If the type of the nested name specifier is the same as the
63 // injected class name of the named class template, we're entering
64 // into that class template definition.
65 QualType Injected = ClassTemplate->getInjectedClassNameType(Context);
Douglas Gregor1930d202009-07-30 17:40:51 +000066 if (Context.hasSameType(Injected, ContextType))
Douglas Gregorb462c322009-07-21 23:53:31 +000067 return ClassTemplate->getTemplatedDecl();
68
Douglas Gregor1930d202009-07-30 17:40:51 +000069 // If the type of the nested name specifier is the same as the
70 // type of one of the class template's class template partial
71 // specializations, we're entering into the definition of that
72 // class template partial specialization.
73 if (ClassTemplatePartialSpecializationDecl *PartialSpec
74 = ClassTemplate->findPartialSpecialization(ContextType))
75 return PartialSpec;
Douglas Gregorb462c322009-07-21 23:53:31 +000076 }
Douglas Gregorc03d3302009-08-25 22:51:20 +000077 } else if (const RecordType *RecordT
78 = dyn_cast_or_null<RecordType>(NNS->getAsType())) {
79 // The nested name specifier refers to a member of a class template.
80 return RecordT->getDecl();
Douglas Gregorb462c322009-07-21 23:53:31 +000081 }
82 }
83
84 return 0;
Douglas Gregor3eb20702009-05-11 19:58:34 +000085 }
Douglas Gregor1e589cc2009-03-26 23:50:42 +000086
87 switch (NNS->getKind()) {
88 case NestedNameSpecifier::Identifier:
89 assert(false && "Dependent nested-name-specifier has no DeclContext");
90 break;
91
92 case NestedNameSpecifier::Namespace:
93 return NNS->getAsNamespace();
94
95 case NestedNameSpecifier::TypeSpec:
96 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +000097 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
Douglas Gregor1e589cc2009-03-26 23:50:42 +000098 assert(Tag && "Non-tag type in nested-name-specifier");
99 return Tag->getDecl();
100 } break;
101
102 case NestedNameSpecifier::Global:
103 return Context.getTranslationUnitDecl();
104 }
105
106 // Required to silence a GCC warning.
107 return 0;
Douglas Gregor253fc4d2009-03-18 00:36:05 +0000108}
109
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000110bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
111 if (!SS.isSet() || SS.isInvalid())
112 return false;
113
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000114 NestedNameSpecifier *NNS
Douglas Gregor041e9292009-03-26 23:56:24 +0000115 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000116 return NNS->isDependent();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000117}
118
Douglas Gregor3eb20702009-05-11 19:58:34 +0000119// \brief Determine whether this C++ scope specifier refers to an
120// unknown specialization, i.e., a dependent type that is not the
121// current instantiation.
122bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
123 if (!isDependentScopeSpecifier(SS))
124 return false;
125
126 NestedNameSpecifier *NNS
127 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
128 return getCurrentInstantiationOf(NNS) == 0;
129}
130
131/// \brief If the given nested name specifier refers to the current
132/// instantiation, return the declaration that corresponds to that
133/// current instantiation (C++0x [temp.dep.type]p1).
134///
135/// \param NNS a dependent nested name specifier.
136CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
137 assert(getLangOptions().CPlusPlus && "Only callable in C++");
138 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
139
Douglas Gregorb462c322009-07-21 23:53:31 +0000140 if (!NNS->getAsType())
141 return 0;
142
Douglas Gregoraf48afe2009-07-31 18:32:42 +0000143 QualType T = QualType(NNS->getAsType(), 0);
Douglas Gregor3eb20702009-05-11 19:58:34 +0000144 // If the nested name specifier does not refer to a type, then it
145 // does not refer to the current instantiation.
146 if (T.isNull())
147 return 0;
148
149 T = Context.getCanonicalType(T);
150
151 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
152 // If we've hit a namespace or the global scope, then the
153 // nested-name-specifier can't refer to the current instantiation.
154 if (Ctx->isFileContext())
155 return 0;
156
157 // Skip non-class contexts.
158 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
159 if (!Record)
160 continue;
161
162 // If this record type is not dependent,
163 if (!Record->isDependentType())
164 return 0;
165
166 // C++ [temp.dep.type]p1:
167 //
168 // In the definition of a class template, a nested class of a
169 // class template, a member of a class template, or a member of a
170 // nested class of a class template, a name refers to the current
171 // instantiation if it is
172 // -- the injected-class-name (9) of the class template or
173 // nested class,
174 // -- in the definition of a primary class template, the name
175 // of the class template followed by the template argument
176 // list of the primary template (as described below)
177 // enclosed in <>,
178 // -- in the definition of a nested class of a class template,
179 // the name of the nested class referenced as a member of
180 // the current instantiation, or
181 // -- in the definition of a partial specialization, the name
182 // of the class template followed by the template argument
183 // list of the partial specialization enclosed in <>. If
184 // the nth template parameter is a parameter pack, the nth
185 // template argument is a pack expansion (14.6.3) whose
Douglas Gregorc1d25252009-07-30 17:50:56 +0000186 // pattern is the name of the parameter pack.
187 // (FIXME: parameter packs)
Douglas Gregor3eb20702009-05-11 19:58:34 +0000188 //
189 // All of these options come down to having the
190 // nested-name-specifier type that is equivalent to the
191 // injected-class-name of one of the types that is currently in
192 // our context.
Douglas Gregorb462c322009-07-21 23:53:31 +0000193 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor3eb20702009-05-11 19:58:34 +0000194 return Record;
195
196 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
197 QualType InjectedClassName
198 = Template->getInjectedClassNameType(Context);
199 if (T == Context.getCanonicalType(InjectedClassName))
200 return Template->getTemplatedDecl();
201 }
Douglas Gregor1930d202009-07-30 17:40:51 +0000202 // FIXME: check for class template partial specializations
Douglas Gregor3eb20702009-05-11 19:58:34 +0000203 }
204
205 return 0;
206}
207
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000208/// \brief Require that the context specified by SS be complete.
209///
210/// If SS refers to a type, this routine checks whether the type is
211/// complete enough (or can be made complete enough) for name lookup
212/// into the DeclContext. A type that is not yet completed can be
213/// considered "complete enough" if it is a class/struct/union/enum
214/// that is currently being defined. Or, if we have a type that names
215/// a class template specialization that is not a complete type, we
216/// will attempt to instantiate that class template.
217bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
218 if (!SS.isSet() || SS.isInvalid())
219 return false;
220
Douglas Gregor84a20812009-07-22 23:48:44 +0000221 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000222 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
223 // If we're currently defining this type, then lookup into the
224 // type is okay: don't complain that it isn't complete yet.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000225 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000226 if (TagT->isBeingDefined())
227 return false;
228
229 // The type must be complete.
230 return RequireCompleteType(SS.getRange().getBegin(),
231 Context.getTypeDeclType(Tag),
232 diag::err_incomplete_nested_name_spec,
233 SS.getRange());
234 }
235
236 return false;
237}
Cédric Venet31c94022009-02-14 20:20:19 +0000238
239/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
240/// global scope ('::').
241Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
242 SourceLocation CCLoc) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000243 return NestedNameSpecifier::GlobalSpecifier(Context);
Cédric Venet31c94022009-02-14 20:20:19 +0000244}
245
246/// ActOnCXXNestedNameSpecifier - Called during parsing of a
247/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
248/// we want to resolve "bar::". 'SS' is empty or the previously parsed
249/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
250/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
251/// Returns a CXXScopeTy* object representing the C++ scope.
252Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
253 const CXXScopeSpec &SS,
254 SourceLocation IdLoc,
255 SourceLocation CCLoc,
Douglas Gregorc03d3302009-08-25 22:51:20 +0000256 IdentifierInfo &II,
257 bool EnteringContext) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000258 NestedNameSpecifier *Prefix
Douglas Gregor041e9292009-03-26 23:56:24 +0000259 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000260
Douglas Gregorc03d3302009-08-25 22:51:20 +0000261 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName,
262 false, false, SourceLocation(),
263 EnteringContext);
Cédric Venet31c94022009-02-14 20:20:19 +0000264
265 if (SD) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000266 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
267 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cédric Venet31c94022009-02-14 20:20:19 +0000268
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000269 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
270 // Determine whether we have a class (or, in C++0x, an enum) or
271 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord3022602009-03-27 23:10:48 +0000272 QualType T = Context.getTypeDeclType(Type);
273 bool AcceptableType = false;
274 if (T->isDependentType())
275 AcceptableType = true;
276 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000277 if (TD->getUnderlyingType()->isRecordType() ||
278 (getLangOptions().CPlusPlus0x &&
279 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord3022602009-03-27 23:10:48 +0000280 AcceptableType = true;
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000281 } else if (isa<RecordDecl>(Type) ||
282 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord3022602009-03-27 23:10:48 +0000283 AcceptableType = true;
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000284
Douglas Gregord3022602009-03-27 23:10:48 +0000285 if (AcceptableType)
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000286 return NestedNameSpecifier::Create(Context, Prefix, false,
287 T.getTypePtr());
288 }
Anders Carlsson7c1c5482009-03-28 23:53:49 +0000289
Douglas Gregor3e208d82009-08-26 00:04:55 +0000290 // FIXME: It would be nice to maintain the namespace alias name, then
291 // see through that alias when resolving the nested-name-specifier down to
292 // a declaration context.
Anders Carlsson7c1c5482009-03-28 23:53:49 +0000293 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
294 return NestedNameSpecifier::Create(Context, Prefix,
295 Alias->getNamespace());
Cédric Venet31c94022009-02-14 20:20:19 +0000296
297 // Fall through to produce an error: we found something that isn't
298 // a class or a namespace.
Douglas Gregorc03d3302009-08-25 22:51:20 +0000299 } else if (SS.isSet() && isDependentScopeSpecifier(SS))
300 return NestedNameSpecifier::Create(Context, Prefix, &II);
Cédric Venet31c94022009-02-14 20:20:19 +0000301
302 // If we didn't find anything during our lookup, try again with
303 // ordinary name lookup, which can help us produce better error
304 // messages.
305 if (!SD)
Douglas Gregorc03d3302009-08-25 22:51:20 +0000306 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName,
307 false, false, SourceLocation(),
308 EnteringContext);
Cédric Venet31c94022009-02-14 20:20:19 +0000309 unsigned DiagID;
310 if (SD)
311 DiagID = diag::err_expected_class_or_namespace;
312 else if (SS.isSet())
313 DiagID = diag::err_typecheck_no_member;
314 else
315 DiagID = diag::err_undeclared_var_use;
316
317 if (SS.isSet())
318 Diag(IdLoc, DiagID) << &II << SS.getRange();
319 else
320 Diag(IdLoc, DiagID) << &II;
321
322 return 0;
323}
324
Douglas Gregor0c281a82009-02-25 19:37:18 +0000325Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
326 const CXXScopeSpec &SS,
327 TypeTy *Ty,
328 SourceRange TypeRange,
329 SourceLocation CCLoc) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000330 NestedNameSpecifier *Prefix
Douglas Gregor041e9292009-03-26 23:56:24 +0000331 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000332 QualType T = GetTypeFromParser(Ty);
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000333 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor96b6df92009-05-14 00:28:11 +0000334 T.getTypePtr());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000335}
336
Douglas Gregorda61ad22009-08-06 03:17:00 +0000337Action::OwningExprResult
338Sema::ActOnCXXEnterMemberScope(Scope *S, CXXScopeSpec &SS, ExprArg Base,
339 tok::TokenKind OpKind) {
Nate Begemane85f43d2009-08-10 23:49:36 +0000340 // Since this might be a postfix expression, get rid of ParenListExprs.
341 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
342
Douglas Gregorda61ad22009-08-06 03:17:00 +0000343 Expr *BaseExpr = (Expr*)Base.get();
344 assert(BaseExpr && "no record expansion");
345
346 QualType BaseType = BaseExpr->getType();
347 // FIXME: handle dependent types
348 if (BaseType->isDependentType())
349 return move(Base);
350
351 // C++ [over.match.oper]p8:
352 // [...] When operator->returns, the operator-> is applied to the value
353 // returned, with the original second operand.
354 if (OpKind == tok::arrow) {
355 while (BaseType->isRecordType()) {
356 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
357 BaseExpr = (Expr*)Base.get();
358 if (BaseExpr == NULL)
359 return ExprError();
360 BaseType = BaseExpr->getType();
361 }
362 }
363
364 if (BaseType->isPointerType())
365 BaseType = BaseType->getPointeeType();
366
367 // We could end up with various non-record types here, such as extended
368 // vector types or Objective-C interfaces. Just return early and let
369 // ActOnMemberReferenceExpr do the work.
370 if (!BaseType->isRecordType())
371 return move(Base);
372
373 SS.setRange(BaseExpr->getSourceRange());
374 SS.setScopeRep(
375 NestedNameSpecifier::Create(Context, 0, false, BaseType.getTypePtr())
376 );
377
378 if (S)
379 ActOnCXXEnterDeclaratorScope(S,SS);
380 return move(Base);
381}
382
383void Sema::ActOnCXXExitMemberScope(Scope *S, const CXXScopeSpec &SS) {
384 if (S && SS.isSet())
385 ActOnCXXExitDeclaratorScope(S,SS);
386}
387
388
Cédric Venet31c94022009-02-14 20:20:19 +0000389/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
390/// scope or nested-name-specifier) is parsed, part of a declarator-id.
391/// After this method is called, according to [C++ 3.4.3p3], names should be
392/// looked up in the declarator-id's scope, until the declarator is parsed and
393/// ActOnCXXExitDeclaratorScope is called.
394/// The 'SS' should be a non-empty valid CXXScopeSpec.
395void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
396 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorb462c322009-07-21 23:53:31 +0000397 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregorc495faa2009-07-21 18:59:28 +0000398 EnterDeclaratorContext(S, DC);
Cédric Venet31c94022009-02-14 20:20:19 +0000399}
400
401/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
402/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
403/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
404/// Used to indicate that names should revert to being looked up in the
405/// defining scope.
406void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
407 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregor3e208d82009-08-26 00:04:55 +0000408 if (SS.isInvalid())
409 return;
410 if (computeDeclContext(SS, true))
Douglas Gregorc495faa2009-07-21 18:59:28 +0000411 ExitDeclaratorContext(S);
Cédric Venet31c94022009-02-14 20:20:19 +0000412}