blob: e1cba36c82fa553db823c409fedbbfdacb9ce90f [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"
Cedric Venet3d658642009-02-14 20:20:19 +000019#include "clang/Parse/DeclSpec.h"
20#include "llvm/ADT/STLExtras.h"
Douglas Gregor7551c182009-07-22 00:28:09 +000021#include "llvm/Support/raw_ostream.h"
Cedric Venet3d658642009-02-14 20:20:19 +000022using namespace clang;
23
Douglas Gregore4e5b052009-03-19 00:18:19 +000024/// \brief Compute the DeclContext that is associated with the given
25/// scope specifier.
Douglas Gregorf59a56e2009-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 Gregore4e5b052009-03-19 00:18:19 +000039 if (!SS.isSet() || SS.isInvalid())
Douglas Gregorca5e77f2009-03-18 00:36:05 +000040 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +000041
Douglas Gregorab452ba2009-03-26 23:50:42 +000042 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +000043 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor42af25f2009-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 Gregorf59a56e2009-07-21 23:53:31 +000049
50 if (EnteringContext) {
51 // We are entering the context of the nested name specifier, so try to
52 // match the nested name specifier to either a primary class template
Douglas Gregor7551c182009-07-22 00:28:09 +000053 // or a class template partial specialization.
Douglas Gregorf59a56e2009-07-21 23:53:31 +000054 if (const TemplateSpecializationType *SpecType
55 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) {
56 if (ClassTemplateDecl *ClassTemplate
57 = dyn_cast_or_null<ClassTemplateDecl>(
58 SpecType->getTemplateName().getAsTemplateDecl())) {
Douglas Gregorb88e8882009-07-30 17:40:51 +000059 QualType ContextType
60 = Context.getCanonicalType(QualType(SpecType, 0));
61
Douglas Gregorf59a56e2009-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 Gregorb88e8882009-07-30 17:40:51 +000066 if (Context.hasSameType(Injected, ContextType))
Douglas Gregorf59a56e2009-07-21 23:53:31 +000067 return ClassTemplate->getTemplatedDecl();
68
Douglas Gregorb88e8882009-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 Gregorf59a56e2009-07-21 23:53:31 +000076 }
77 }
Douglas Gregor7551c182009-07-22 00:28:09 +000078
79 std::string NNSString;
80 {
81 llvm::raw_string_ostream OS(NNSString);
82 NNS->print(OS, Context.PrintingPolicy);
83 }
84
85 // FIXME: Allow us to pass a nested-name-specifier to Diag?
86 Diag(SS.getRange().getBegin(),
87 diag::err_template_qualified_declarator_no_match)
88 << NNSString << SS.getRange();
Douglas Gregorf59a56e2009-07-21 23:53:31 +000089 }
90
91 return 0;
Douglas Gregor42af25f2009-05-11 19:58:34 +000092 }
Douglas Gregorab452ba2009-03-26 23:50:42 +000093
94 switch (NNS->getKind()) {
95 case NestedNameSpecifier::Identifier:
96 assert(false && "Dependent nested-name-specifier has no DeclContext");
97 break;
98
99 case NestedNameSpecifier::Namespace:
100 return NNS->getAsNamespace();
101
102 case NestedNameSpecifier::TypeSpec:
103 case NestedNameSpecifier::TypeSpecWithTemplate: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000104 const TagType *Tag = NNS->getAsType()->getAs<TagType>();
Douglas Gregorab452ba2009-03-26 23:50:42 +0000105 assert(Tag && "Non-tag type in nested-name-specifier");
106 return Tag->getDecl();
107 } break;
108
109 case NestedNameSpecifier::Global:
110 return Context.getTranslationUnitDecl();
111 }
112
113 // Required to silence a GCC warning.
114 return 0;
Douglas Gregorca5e77f2009-03-18 00:36:05 +0000115}
116
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000117bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
118 if (!SS.isSet() || SS.isInvalid())
119 return false;
120
Douglas Gregorab452ba2009-03-26 23:50:42 +0000121 NestedNameSpecifier *NNS
Douglas Gregor35073692009-03-26 23:56:24 +0000122 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000123 return NNS->isDependent();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000124}
125
Douglas Gregor42af25f2009-05-11 19:58:34 +0000126// \brief Determine whether this C++ scope specifier refers to an
127// unknown specialization, i.e., a dependent type that is not the
128// current instantiation.
129bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
130 if (!isDependentScopeSpecifier(SS))
131 return false;
132
133 NestedNameSpecifier *NNS
134 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
135 return getCurrentInstantiationOf(NNS) == 0;
136}
137
138/// \brief If the given nested name specifier refers to the current
139/// instantiation, return the declaration that corresponds to that
140/// current instantiation (C++0x [temp.dep.type]p1).
141///
142/// \param NNS a dependent nested name specifier.
143CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
144 assert(getLangOptions().CPlusPlus && "Only callable in C++");
145 assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
146
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000147 if (!NNS->getAsType())
148 return 0;
149
Douglas Gregor1560def2009-07-31 18:32:42 +0000150 QualType T = QualType(NNS->getAsType(), 0);
Douglas Gregor42af25f2009-05-11 19:58:34 +0000151 // If the nested name specifier does not refer to a type, then it
152 // does not refer to the current instantiation.
153 if (T.isNull())
154 return 0;
155
156 T = Context.getCanonicalType(T);
157
158 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
159 // If we've hit a namespace or the global scope, then the
160 // nested-name-specifier can't refer to the current instantiation.
161 if (Ctx->isFileContext())
162 return 0;
163
164 // Skip non-class contexts.
165 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
166 if (!Record)
167 continue;
168
169 // If this record type is not dependent,
170 if (!Record->isDependentType())
171 return 0;
172
173 // C++ [temp.dep.type]p1:
174 //
175 // In the definition of a class template, a nested class of a
176 // class template, a member of a class template, or a member of a
177 // nested class of a class template, a name refers to the current
178 // instantiation if it is
179 // -- the injected-class-name (9) of the class template or
180 // nested class,
181 // -- in the definition of a primary class template, the name
182 // of the class template followed by the template argument
183 // list of the primary template (as described below)
184 // enclosed in <>,
185 // -- in the definition of a nested class of a class template,
186 // the name of the nested class referenced as a member of
187 // the current instantiation, or
188 // -- in the definition of a partial specialization, the name
189 // of the class template followed by the template argument
190 // list of the partial specialization enclosed in <>. If
191 // the nth template parameter is a parameter pack, the nth
192 // template argument is a pack expansion (14.6.3) whose
Douglas Gregorc5b8c9b2009-07-30 17:50:56 +0000193 // pattern is the name of the parameter pack.
194 // (FIXME: parameter packs)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000195 //
196 // All of these options come down to having the
197 // nested-name-specifier type that is equivalent to the
198 // injected-class-name of one of the types that is currently in
199 // our context.
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000200 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T)
Douglas Gregor42af25f2009-05-11 19:58:34 +0000201 return Record;
202
203 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
204 QualType InjectedClassName
205 = Template->getInjectedClassNameType(Context);
206 if (T == Context.getCanonicalType(InjectedClassName))
207 return Template->getTemplatedDecl();
208 }
Douglas Gregorb88e8882009-07-30 17:40:51 +0000209 // FIXME: check for class template partial specializations
Douglas Gregor42af25f2009-05-11 19:58:34 +0000210 }
211
212 return 0;
213}
214
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000215/// \brief Require that the context specified by SS be complete.
216///
217/// If SS refers to a type, this routine checks whether the type is
218/// complete enough (or can be made complete enough) for name lookup
219/// into the DeclContext. A type that is not yet completed can be
220/// considered "complete enough" if it is a class/struct/union/enum
221/// that is currently being defined. Or, if we have a type that names
222/// a class template specialization that is not a complete type, we
223/// will attempt to instantiate that class template.
224bool Sema::RequireCompleteDeclContext(const CXXScopeSpec &SS) {
225 if (!SS.isSet() || SS.isInvalid())
226 return false;
227
Douglas Gregor7cdbc582009-07-22 23:48:44 +0000228 DeclContext *DC = computeDeclContext(SS, true);
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000229 if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
230 // If we're currently defining this type, then lookup into the
231 // type is okay: don't complain that it isn't complete yet.
Ted Kremenek6217b802009-07-29 21:53:49 +0000232 const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +0000233 if (TagT->isBeingDefined())
234 return false;
235
236 // The type must be complete.
237 return RequireCompleteType(SS.getRange().getBegin(),
238 Context.getTypeDeclType(Tag),
239 diag::err_incomplete_nested_name_spec,
240 SS.getRange());
241 }
242
243 return false;
244}
Cedric Venet3d658642009-02-14 20:20:19 +0000245
246/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
247/// global scope ('::').
248Sema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
249 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000250 return NestedNameSpecifier::GlobalSpecifier(Context);
Cedric Venet3d658642009-02-14 20:20:19 +0000251}
252
253/// ActOnCXXNestedNameSpecifier - Called during parsing of a
254/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
255/// we want to resolve "bar::". 'SS' is empty or the previously parsed
256/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
257/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
258/// Returns a CXXScopeTy* object representing the C++ scope.
259Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
260 const CXXScopeSpec &SS,
261 SourceLocation IdLoc,
262 SourceLocation CCLoc,
263 IdentifierInfo &II) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000264 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000265 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregorab452ba2009-03-26 23:50:42 +0000266
Douglas Gregor42af25f2009-05-11 19:58:34 +0000267 // If the prefix already refers to an unknown specialization, there
268 // is no name lookup to perform. Just build the resulting
269 // nested-name-specifier.
270 if (Prefix && isUnknownSpecialization(SS))
Douglas Gregorab452ba2009-03-26 23:50:42 +0000271 return NestedNameSpecifier::Create(Context, Prefix, &II);
272
Cedric Venet3d658642009-02-14 20:20:19 +0000273 NamedDecl *SD = LookupParsedName(S, &SS, &II, LookupNestedNameSpecifierName);
274
275 if (SD) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000276 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
277 return NestedNameSpecifier::Create(Context, Prefix, Namespace);
Cedric Venet3d658642009-02-14 20:20:19 +0000278
Douglas Gregorab452ba2009-03-26 23:50:42 +0000279 if (TypeDecl *Type = dyn_cast<TypeDecl>(SD)) {
280 // Determine whether we have a class (or, in C++0x, an enum) or
281 // a typedef thereof. If so, build the nested-name-specifier.
Douglas Gregord57959a2009-03-27 23:10:48 +0000282 QualType T = Context.getTypeDeclType(Type);
283 bool AcceptableType = false;
284 if (T->isDependentType())
285 AcceptableType = true;
286 else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000287 if (TD->getUnderlyingType()->isRecordType() ||
288 (getLangOptions().CPlusPlus0x &&
289 TD->getUnderlyingType()->isEnumeralType()))
Douglas Gregord57959a2009-03-27 23:10:48 +0000290 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000291 } else if (isa<RecordDecl>(Type) ||
292 (getLangOptions().CPlusPlus0x && isa<EnumDecl>(Type)))
Douglas Gregord57959a2009-03-27 23:10:48 +0000293 AcceptableType = true;
Douglas Gregorab452ba2009-03-26 23:50:42 +0000294
Douglas Gregord57959a2009-03-27 23:10:48 +0000295 if (AcceptableType)
Douglas Gregorab452ba2009-03-26 23:50:42 +0000296 return NestedNameSpecifier::Create(Context, Prefix, false,
297 T.getTypePtr());
298 }
Anders Carlsson81c85c42009-03-28 23:53:49 +0000299
300 if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
301 return NestedNameSpecifier::Create(Context, Prefix,
302 Alias->getNamespace());
Cedric Venet3d658642009-02-14 20:20:19 +0000303
304 // Fall through to produce an error: we found something that isn't
305 // a class or a namespace.
306 }
307
308 // If we didn't find anything during our lookup, try again with
309 // ordinary name lookup, which can help us produce better error
310 // messages.
311 if (!SD)
312 SD = LookupParsedName(S, &SS, &II, LookupOrdinaryName);
313 unsigned DiagID;
314 if (SD)
315 DiagID = diag::err_expected_class_or_namespace;
316 else if (SS.isSet())
317 DiagID = diag::err_typecheck_no_member;
318 else
319 DiagID = diag::err_undeclared_var_use;
320
321 if (SS.isSet())
322 Diag(IdLoc, DiagID) << &II << SS.getRange();
323 else
324 Diag(IdLoc, DiagID) << &II;
325
326 return 0;
327}
328
Douglas Gregor39a8de12009-02-25 19:37:18 +0000329Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
330 const CXXScopeSpec &SS,
331 TypeTy *Ty,
332 SourceRange TypeRange,
333 SourceLocation CCLoc) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000334 NestedNameSpecifier *Prefix
Douglas Gregor35073692009-03-26 23:56:24 +0000335 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000336 QualType T = QualType::getFromOpaquePtr(Ty);
Douglas Gregorab452ba2009-03-26 23:50:42 +0000337 return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +0000338 T.getTypePtr());
Douglas Gregor39a8de12009-02-25 19:37:18 +0000339}
340
Douglas Gregorfe85ced2009-08-06 03:17:00 +0000341Action::OwningExprResult
342Sema::ActOnCXXEnterMemberScope(Scope *S, CXXScopeSpec &SS, ExprArg Base,
343 tok::TokenKind OpKind) {
344 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);
400 else
401 const_cast<CXXScopeSpec&>(SS).setScopeRep(0);
Cedric Venet3d658642009-02-14 20:20:19 +0000402}
403
404/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
405/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
406/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
407/// Used to indicate that names should revert to being looked up in the
408/// defining scope.
409void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
410 assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
Douglas Gregorf59a56e2009-07-21 23:53:31 +0000411 assert((SS.isInvalid() || S->getEntity() == computeDeclContext(SS, true)) &&
Douglas Gregor3fdbed52009-07-21 18:59:28 +0000412 "Context imbalance!");
413 if (!SS.isInvalid())
414 ExitDeclaratorContext(S);
Cedric Venet3d658642009-02-14 20:20:19 +0000415}