blob: 9c9bff8a085de94a3d1c89d56e52a2e1fedfc081 [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 }
Douglas Gregor179bcef2009-07-22 00:28:09 +000082
83 std::string NNSString;
84 {
85 llvm::raw_string_ostream OS(NNSString);
86 NNS->print(OS, Context.PrintingPolicy);
87 }
88
89 // FIXME: Allow us to pass a nested-name-specifier to Diag?
90 Diag(SS.getRange().getBegin(),
91 diag::err_template_qualified_declarator_no_match)
92 << NNSString << SS.getRange();
Douglas Gregorb462c322009-07-21 23:53:31 +000093 }
94
95 return 0;
Douglas Gregor3eb20702009-05-11 19:58:34 +000096 }
Douglas Gregor1e589cc2009-03-26 23:50:42 +000097
98 switch (NNS->getKind()) {
99 case NestedNameSpecifier::Identifier:
100 assert(false && "Dependent nested-name-specifier has no DeclContext");
101 break;
102
103 case NestedNameSpecifier::Namespace:
104 return NNS->getAsNamespace();
105
106 case NestedNameSpecifier::TypeSpec:
107 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000108 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000109 assert(Tag && "Non-tag type in nested-name-specifier");
110 return Tag->getDecl();
111 } break;
112
113 case NestedNameSpecifier::Global:
114 return Context.getTranslationUnitDecl();
115 }
116
117 // Required to silence a GCC warning.
118 return 0;
Douglas Gregor253fc4d2009-03-18 00:36:05 +0000119}
120
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000121bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
122 if (!SS.isSet() || SS.isInvalid())
123 return false;
124
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000125 NestedNameSpecifier *NNS
Douglas Gregor041e9292009-03-26 23:56:24 +0000126 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000127 return NNS->isDependent();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000128}
129
Douglas Gregor3eb20702009-05-11 19:58:34 +0000130// \brief Determine whether this C++ scope specifier refers to an
131// unknown specialization, i.e., a dependent type that is not the
132// current instantiation.
133bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
134 if (!isDependentScopeSpecifier(SS))
135 return false;
136
137 NestedNameSpecifier *NNS
138 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
139 return getCurrentInstantiationOf(NNS) == 0;
140}
141
142/// \brief If the given nested name specifier refers to the current
143/// instantiation, return the declaration that corresponds to that
144/// current instantiation (C++0x [temp.dep.type]p1).
145///
146/// \param NNS a dependent nested name specifier.
147CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
148 assert(getLangOptions().CPlusPlus && "Only callable in C++");
149 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
150
Douglas Gregorb462c322009-07-21 23:53:31 +0000151 if (!NNS->getAsType())
152 return 0;
153
Douglas Gregoraf48afe2009-07-31 18:32:42 +0000154 QualType T = QualType(NNS->getAsType(), 0);
Douglas Gregor3eb20702009-05-11 19:58:34 +0000155 // If the nested name specifier does not refer to a type, then it
156 // does not refer to the current instantiation.
157 if (T.isNull())
158 return 0;
159
160 T = Context.getCanonicalType(T);
161
162 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
163 // If we've hit a namespace or the global scope, then the
164 // nested-name-specifier can't refer to the current instantiation.
165 if (Ctx->isFileContext())
166 return 0;
167
168 // Skip non-class contexts.
169 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
170 if (!Record)
171 continue;
172
173 // If this record type is not dependent,
174 if (!Record->isDependentType())
175 return 0;
176
177 // C++ [temp.dep.type]p1:
178 //
179 // In the definition of a class template, a nested class of a
180 // class template, a member of a class template, or a member of a
181 // nested class of a class template, a name refers to the current
182 // instantiation if it is
183 // -- the injected-class-name (9) of the class template or
184 // nested class,
185 // -- in the definition of a primary class template, the name
186 // of the class template followed by the template argument
187 // list of the primary template (as described below)
188 // enclosed in <>,
189 // -- in the definition of a nested class of a class template,
190 // the name of the nested class referenced as a member of
191 // the current instantiation, or
192 // -- in the definition of a partial specialization, the name
193 // of the class template followed by the template argument
194 // list of the partial specialization enclosed in <>. If
195 // the nth template parameter is a parameter pack, the nth
196 // template argument is a pack expansion (14.6.3) whose
Douglas Gregorc1d25252009-07-30 17:50:56 +0000197 // pattern is the name of the parameter pack.
198 // (FIXME: parameter packs)
Douglas Gregor3eb20702009-05-11 19:58:34 +0000199 //
200 // All of these options come down to having the
201 // nested-name-specifier type that is equivalent to the
202 // injected-class-name of one of the types that is currently in
203 // our context.
Douglas Gregorb462c322009-07-21 23:53:31 +0000204 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor3eb20702009-05-11 19:58:34 +0000205 return Record;
206
207 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
208 QualType InjectedClassName
209 = Template->getInjectedClassNameType(Context);
210 if (T == Context.getCanonicalType(InjectedClassName))
211 return Template->getTemplatedDecl();
212 }
Douglas Gregor1930d202009-07-30 17:40:51 +0000213 // FIXME: check for class template partial specializations
Douglas Gregor3eb20702009-05-11 19:58:34 +0000214 }
215
216 return 0;
217}
218
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000219/// \brief Require that the context specified by SS be complete.
220///
221/// If SS refers to a type, this routine checks whether the type is
222/// complete enough (or can be made complete enough) for name lookup
223/// into the DeclContext. A type that is not yet completed can be
224/// considered "complete enough" if it is a class/struct/union/enum
225/// that is currently being defined. Or, if we have a type that names
226/// a class template specialization that is not a complete type, we
227/// will attempt to instantiate that class template.
228bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
229 if (!SS.isSet() || SS.isInvalid())
230 return false;
231
Douglas Gregor84a20812009-07-22 23:48:44 +0000232 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000233 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
234 // If we're currently defining this type, then lookup into the
235 // type is okay: don't complain that it isn't complete yet.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000236 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor6e7c27c2009-03-11 16:48:53 +0000237 if (TagT->isBeingDefined())
238 return false;
239
240 // The type must be complete.
241 return RequireCompleteType(SS.getRange().getBegin(),
242 Context.getTypeDeclType(Tag),
243 diag::err_incomplete_nested_name_spec,
244 SS.getRange());
245 }
246
247 return false;
248}
Cédric Venet31c94022009-02-14 20:20:19 +0000249
250/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
251/// global scope ('::').
252Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
253 SourceLocation CCLoc) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000254 return NestedNameSpecifier::GlobalSpecifier(Context);
Cédric Venet31c94022009-02-14 20:20:19 +0000255}
256
257/// ActOnCXXNestedNameSpecifier - Called during parsing of a
258/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
259/// we want to resolve "bar::". 'SS' is empty or the previously parsed
260/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
261/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
262/// Returns a CXXScopeTy* object representing the C++ scope.
263Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
264 const CXXScopeSpec &SS,
265 SourceLocation IdLoc,
266 SourceLocation CCLoc,
Douglas Gregorc03d3302009-08-25 22:51:20 +0000267 IdentifierInfo &II,
268 bool EnteringContext) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000269 NestedNameSpecifier *Prefix
Douglas Gregor041e9292009-03-26 23:56:24 +0000270 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000271
Douglas Gregorc03d3302009-08-25 22:51:20 +0000272 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName,
273 false, false, SourceLocation(),
274 EnteringContext);
Cédric Venet31c94022009-02-14 20:20:19 +0000275
276 if (SD) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000277 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
278 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cédric Venet31c94022009-02-14 20:20:19 +0000279
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000280 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
281 // Determine whether we have a class (or, in C++0x, an enum) or
282 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord3022602009-03-27 23:10:48 +0000283 QualType T = Context.getTypeDeclType(Type);
284 bool AcceptableType = false;
285 if (T->isDependentType())
286 AcceptableType = true;
287 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000288 if (TD->getUnderlyingType()->isRecordType() ||
289 (getLangOptions().CPlusPlus0x &&
290 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord3022602009-03-27 23:10:48 +0000291 AcceptableType = true;
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000292 } else if (isa<RecordDecl>(Type) ||
293 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord3022602009-03-27 23:10:48 +0000294 AcceptableType = true;
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000295
Douglas Gregord3022602009-03-27 23:10:48 +0000296 if (AcceptableType)
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000297 return NestedNameSpecifier::Create(Context, Prefix, false,
298 T.getTypePtr());
299 }
Anders Carlsson7c1c5482009-03-28 23:53:49 +0000300
301 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
302 return NestedNameSpecifier::Create(Context, Prefix,
303 Alias->getNamespace());
Cédric Venet31c94022009-02-14 20:20:19 +0000304
305 // Fall through to produce an error: we found something that isn't
306 // a class or a namespace.
Douglas Gregorc03d3302009-08-25 22:51:20 +0000307 } else if (SS.isSet() && isDependentScopeSpecifier(SS))
308 return NestedNameSpecifier::Create(Context, Prefix, &II);
Cédric Venet31c94022009-02-14 20:20:19 +0000309
310 // If we didn't find anything during our lookup, try again with
311 // ordinary name lookup, which can help us produce better error
312 // messages.
313 if (!SD)
Douglas Gregorc03d3302009-08-25 22:51:20 +0000314 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName,
315 false, false, SourceLocation(),
316 EnteringContext);
Cédric Venet31c94022009-02-14 20:20:19 +0000317 unsigned DiagID;
318 if (SD)
319 DiagID = diag::err_expected_class_or_namespace;
320 else if (SS.isSet())
321 DiagID = diag::err_typecheck_no_member;
322 else
323 DiagID = diag::err_undeclared_var_use;
324
325 if (SS.isSet())
326 Diag(IdLoc, DiagID) << &II << SS.getRange();
327 else
328 Diag(IdLoc, DiagID) << &II;
329
330 return 0;
331}
332
Douglas Gregor0c281a82009-02-25 19:37:18 +0000333Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
334 const CXXScopeSpec &SS,
335 TypeTy *Ty,
336 SourceRange TypeRange,
337 SourceLocation CCLoc) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000338 NestedNameSpecifier *Prefix
Douglas Gregor041e9292009-03-26 23:56:24 +0000339 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000340 QualType T = GetTypeFromParser(Ty);
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000341 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor96b6df92009-05-14 00:28:11 +0000342 T.getTypePtr());
Douglas Gregor0c281a82009-02-25 19:37:18 +0000343}
344
Douglas Gregorda61ad22009-08-06 03:17:00 +0000345Action::OwningExprResult
346Sema::ActOnCXXEnterMemberScope(Scope *S, CXXScopeSpec &SS, ExprArg Base,
347 tok::TokenKind OpKind) {
Nate Begemane85f43d2009-08-10 23:49:36 +0000348 // Since this might be a postfix expression, get rid of ParenListExprs.
349 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
350
Douglas Gregorda61ad22009-08-06 03:17:00 +0000351 Expr *BaseExpr = (Expr*)Base.get();
352 assert(BaseExpr && "no record expansion");
353
354 QualType BaseType = BaseExpr->getType();
355 // FIXME: handle dependent types
356 if (BaseType->isDependentType())
357 return move(Base);
358
359 // C++ [over.match.oper]p8:
360 // [...] When operator->returns, the operator-> is applied to the value
361 // returned, with the original second operand.
362 if (OpKind == tok::arrow) {
363 while (BaseType->isRecordType()) {
364 Base = BuildOverloadedArrowExpr(S, move(Base), BaseExpr->getExprLoc());
365 BaseExpr = (Expr*)Base.get();
366 if (BaseExpr == NULL)
367 return ExprError();
368 BaseType = BaseExpr->getType();
369 }
370 }
371
372 if (BaseType->isPointerType())
373 BaseType = BaseType->getPointeeType();
374
375 // We could end up with various non-record types here, such as extended
376 // vector types or Objective-C interfaces. Just return early and let
377 // ActOnMemberReferenceExpr do the work.
378 if (!BaseType->isRecordType())
379 return move(Base);
380
381 SS.setRange(BaseExpr->getSourceRange());
382 SS.setScopeRep(
383 NestedNameSpecifier::Create(Context, 0, false, BaseType.getTypePtr())
384 );
385
386 if (S)
387 ActOnCXXEnterDeclaratorScope(S,SS);
388 return move(Base);
389}
390
391void Sema::ActOnCXXExitMemberScope(Scope *S, const CXXScopeSpec &SS) {
392 if (S && SS.isSet())
393 ActOnCXXExitDeclaratorScope(S,SS);
394}
395
396
Cédric Venet31c94022009-02-14 20:20:19 +0000397/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
398/// scope or nested-name-specifier) is parsed, part of a declarator-id.
399/// After this method is called, according to [C++ 3.4.3p3], names should be
400/// looked up in the declarator-id's scope, until the declarator is parsed and
401/// ActOnCXXExitDeclaratorScope is called.
402/// The 'SS' should be a non-empty valid CXXScopeSpec.
403void Sema::ActOnCXXEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
404 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorb462c322009-07-21 23:53:31 +0000405 if (DeclContext *DC = computeDeclContext(SS, true))
Douglas Gregorc495faa2009-07-21 18:59:28 +0000406 EnterDeclaratorContext(S, DC);
407 else
408 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cédric Venet31c94022009-02-14 20:20:19 +0000409}
410
411/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
412/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
413/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
414/// Used to indicate that names should revert to being looked up in the
415/// defining scope.
416void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
417 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorb462c322009-07-21 23:53:31 +0000418 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregorc495faa2009-07-21 18:59:28 +0000419 "Context imbalance!");
420 if (!SS.isInvalid())
421 ExitDeclaratorContext(S);
Cédric Venet31c94022009-02-14 20:20:19 +0000422}