SemaCXXScopeSpec.cpp revision 212904
1193323Sed//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements C++ semantic analysis for scope specifiers.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "clang/Sema/SemaInternal.h"
15193323Sed#include "clang/Sema/Lookup.h"
16193323Sed#include "clang/AST/ASTContext.h"
17206274Srdivacky#include "clang/AST/DeclTemplate.h"
18208599Srdivacky#include "clang/AST/ExprCXX.h"
19221345Sdim#include "clang/AST/NestedNameSpecifier.h"
20193323Sed#include "clang/Basic/PartialDiagnostic.h"
21202878Srdivacky#include "clang/Sema/DeclSpec.h"
22193323Sed#include "llvm/ADT/STLExtras.h"
23206274Srdivacky#include "llvm/Support/raw_ostream.h"
24193323Sedusing namespace clang;
25193323Sed
26206274Srdivacky/// \brief Find the current instantiation that associated with the given type.
27218893Sdimstatic CXXRecordDecl *getCurrentInstantiationOf(QualType T) {
28193323Sed  if (T.isNull())
29193323Sed    return 0;
30193323Sed
31193323Sed  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
32199481Srdivacky  if (isa<RecordType>(Ty))
33199481Srdivacky    return cast<CXXRecordDecl>(cast<RecordType>(Ty)->getDecl());
34193323Sed  else if (isa<InjectedClassNameType>(Ty))
35193323Sed    return cast<InjectedClassNameType>(Ty)->getDecl();
36193323Sed  else
37207618Srdivacky    return 0;
38198090Srdivacky}
39206274Srdivacky
40206274Srdivacky/// \brief Compute the DeclContext that is associated with the given type.
41206274Srdivacky///
42206274Srdivacky/// \param T the type for which we are attempting to find a DeclContext.
43193323Sed///
44193323Sed/// \returns the declaration context represented by the type T,
45193323Sed/// or NULL if the declaration context cannot be computed (e.g., because it is
46193323Sed/// dependent and not the current instantiation).
47199481SrdivackyDeclContext *Sema::computeDeclContext(QualType T) {
48193323Sed  if (const TagType *Tag = T->getAs<TagType>())
49193323Sed    return Tag->getDecl();
50193323Sed
51205218Srdivacky  return ::getCurrentInstantiationOf(T);
52193323Sed}
53205218Srdivacky
54205218Srdivacky/// \brief Compute the DeclContext that is associated with the given
55193323Sed/// scope specifier.
56193323Sed///
57193323Sed/// \param SS the C++ scope specifier as it appears in the source
58193323Sed///
59193323Sed/// \param EnteringContext when true, we will be entering the context of
60205218Srdivacky/// this scope specifier, so we can retrieve the declaration context of a
61193323Sed/// class template or class template partial specialization even if it is
62193323Sed/// not the current instantiation.
63218893Sdim///
64218893Sdim/// \returns the declaration context represented by the scope specifier @p SS,
65218893Sdim/// or NULL if the declaration context cannot be computed (e.g., because it is
66218893Sdim/// dependent and not the current instantiation).
67218893SdimDeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
68218893Sdim                                      bool EnteringContext) {
69221345Sdim  if (!SS.isSet() || SS.isInvalid())
70218893Sdim    return 0;
71223017Sdim
72223017Sdim  NestedNameSpecifier *NNS
73223017Sdim    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
74223017Sdim  if (NNS->isDependent()) {
75223017Sdim    // If this nested-name-specifier refers to the current
76221345Sdim    // instantiation, return its DeclContext.
77221345Sdim    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
78223017Sdim      return Record;
79223017Sdim
80223017Sdim    if (EnteringContext) {
81223017Sdim      const Type *NNSType = NNS->getAsType();
82223017Sdim      if (!NNSType) {
83223017Sdim        // do nothing, fall out
84218893Sdim      } else if (const TemplateSpecializationType *SpecType
85218893Sdim                   = NNSType->getAs<TemplateSpecializationType>()) {
86218893Sdim        // We are entering the context of the nested name specifier, so try to
87218893Sdim        // match the nested name specifier to either a primary class template
88218893Sdim        // or a class template partial specialization.
89218893Sdim        if (ClassTemplateDecl *ClassTemplate
90218893Sdim              = dyn_cast_or_null<ClassTemplateDecl>(
91218893Sdim                            SpecType->getTemplateName().getAsTemplateDecl())) {
92218893Sdim          QualType ContextType
93218893Sdim            = Context.getCanonicalType(QualType(SpecType, 0));
94223017Sdim
95223017Sdim          // If the type of the nested name specifier is the same as the
96218893Sdim          // injected class name of the named class template, we're entering
97218893Sdim          // into that class template definition.
98221345Sdim          QualType Injected
99221345Sdim            = ClassTemplate->getInjectedClassNameSpecialization();
100221345Sdim          if (Context.hasSameType(Injected, ContextType))
101221345Sdim            return ClassTemplate->getTemplatedDecl();
102221345Sdim
103221345Sdim          // If the type of the nested name specifier is the same as the
104221345Sdim          // type of one of the class template's class template partial
105221345Sdim          // specializations, we're entering into the definition of that
106221345Sdim          // class template partial specialization.
107221345Sdim          if (ClassTemplatePartialSpecializationDecl *PartialSpec
108221345Sdim                = ClassTemplate->findPartialSpecialization(ContextType))
109221345Sdim            return PartialSpec;
110221345Sdim        }
111221345Sdim      } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
112221345Sdim        // The nested name specifier refers to a member of a class template.
113221345Sdim        return RecordT->getDecl();
114221345Sdim      }
115221345Sdim    }
116221345Sdim
117221345Sdim    return 0;
118221345Sdim  }
119221345Sdim
120221345Sdim  switch (NNS->getKind()) {
121221345Sdim  case NestedNameSpecifier::Identifier:
122221345Sdim    assert(false && "Dependent nested-name-specifier has no DeclContext");
123221345Sdim    break;
124221345Sdim
125221345Sdim  case NestedNameSpecifier::Namespace:
126221345Sdim    return NNS->getAsNamespace();
127221345Sdim
128221345Sdim  case NestedNameSpecifier::TypeSpec:
129221345Sdim  case NestedNameSpecifier::TypeSpecWithTemplate: {
130221345Sdim    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
131221345Sdim    assert(Tag && "Non-tag type in nested-name-specifier");
132221345Sdim    return Tag->getDecl();
133221345Sdim  } break;
134221345Sdim
135206274Srdivacky  case NestedNameSpecifier::Global:
136206274Srdivacky    return Context.getTranslationUnitDecl();
137206274Srdivacky  }
138206274Srdivacky
139206274Srdivacky  // Required to silence a GCC warning.
140206274Srdivacky  return 0;
141206274Srdivacky}
142193323Sed
143193323Sedbool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
144193323Sed  if (!SS.isSet() || SS.isInvalid())
145193323Sed    return false;
146208599Srdivacky
147208599Srdivacky  NestedNameSpecifier *NNS
148193323Sed    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
149193323Sed  return NNS->isDependent();
150193323Sed}
151193323Sed
152193323Sed// \brief Determine whether this C++ scope specifier refers to an
153193323Sed// unknown specialization, i.e., a dependent type that is not the
154193323Sed// current instantiation.
155193323Sedbool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
156193323Sed  if (!isDependentScopeSpecifier(SS))
157193323Sed    return false;
158193323Sed
159218893Sdim  NestedNameSpecifier *NNS
160193323Sed    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
161205218Srdivacky  return getCurrentInstantiationOf(NNS) == 0;
162205218Srdivacky}
163205218Srdivacky
164205218Srdivacky/// \brief If the given nested name specifier refers to the current
165205218Srdivacky/// instantiation, return the declaration that corresponds to that
166205218Srdivacky/// current instantiation (C++0x [temp.dep.type]p1).
167193323Sed///
168193323Sed/// \param NNS a dependent nested name specifier.
169193323SedCXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
170198090Srdivacky  assert(getLangOptions().CPlusPlus && "Only callable in C++");
171193323Sed  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
172221345Sdim
173221345Sdim  if (!NNS->getAsType())
174199481Srdivacky    return 0;
175193323Sed
176221345Sdim  QualType T = QualType(NNS->getAsType(), 0);
177221345Sdim  return ::getCurrentInstantiationOf(T);
178221345Sdim}
179205218Srdivacky
180205218Srdivacky/// \brief Require that the context specified by SS be complete.
181199481Srdivacky///
182208599Srdivacky/// If SS refers to a type, this routine checks whether the type is
183193323Sed/// complete enough (or can be made complete enough) for name lookup
184199481Srdivacky/// into the DeclContext. A type that is not yet completed can be
185199481Srdivacky/// considered "complete enough" if it is a class/struct/union/enum
186208599Srdivacky/// that is currently being defined. Or, if we have a type that names
187199481Srdivacky/// a class template specialization that is not a complete type, we
188199481Srdivacky/// will attempt to instantiate that class template.
189205218Srdivackybool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
190208599Srdivacky                                      DeclContext *DC) {
191206083Srdivacky  assert(DC != 0 && "given null context");
192210299Sed
193210299Sed  if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
194210299Sed    // If this is a dependent type, then we consider it complete.
195206083Srdivacky    if (Tag->isDependentContext())
196206083Srdivacky      return false;
197199481Srdivacky
198199481Srdivacky    // If we're currently defining this type, then lookup into the
199205218Srdivacky    // type is okay: don't complain that it isn't complete yet.
200205218Srdivacky    const TagType *TagT = Context.getTypeDeclType(Tag)->getAs<TagType>();
201208599Srdivacky    if (TagT && TagT->isBeingDefined())
202199481Srdivacky      return false;
203208599Srdivacky
204208599Srdivacky    // The type must be complete.
205208599Srdivacky    if (RequireCompleteType(SS.getRange().getBegin(),
206206083Srdivacky                            Context.getTypeDeclType(Tag),
207208599Srdivacky                            PDiag(diag::err_incomplete_nested_name_spec)
208208599Srdivacky                              << SS.getRange())) {
209208599Srdivacky      SS.setScopeRep(0);  // Mark the ScopeSpec invalid.
210208599Srdivacky      return true;
211208599Srdivacky    }
212208599Srdivacky  }
213208599Srdivacky
214208599Srdivacky  return false;
215208599Srdivacky}
216208599Srdivacky
217208599Srdivacky/// ActOnCXXGlobalScopeSpecifier - Return the object that represents the
218208599Srdivacky/// global scope ('::').
219208599SrdivackySema::CXXScopeTy *Sema::ActOnCXXGlobalScopeSpecifier(Scope *S,
220208599Srdivacky                                                     SourceLocation CCLoc) {
221208599Srdivacky  return NestedNameSpecifier::GlobalSpecifier(Context);
222199481Srdivacky}
223199481Srdivacky
224199481Srdivacky/// \brief Determines whether the given declaration is an valid acceptable
225199481Srdivacky/// result for name lookup of a nested-name-specifier.
226207618Srdivackybool Sema::isAcceptableNestedNameSpecifier(NamedDecl *SD) {
227207618Srdivacky  if (!SD)
228207618Srdivacky    return false;
229208599Srdivacky
230200581Srdivacky  // Namespace and namespace aliases are fine.
231193323Sed  if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
232193323Sed    return true;
233208599Srdivacky
234208599Srdivacky  if (!isa<TypeDecl>(SD))
235208599Srdivacky    return false;
236193323Sed
237210299Sed  // Determine whether we have a class (or, in C++0x, an enum) or
238210299Sed  // a typedef thereof. If so, build the nested-name-specifier.
239210299Sed  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
240210299Sed  if (T->isDependentType())
241207618Srdivacky    return true;
242207618Srdivacky  else if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
243207618Srdivacky    if (TD->getUnderlyingType()->isRecordType() ||
244193323Sed        (Context.getLangOptions().CPlusPlus0x &&
245207618Srdivacky         TD->getUnderlyingType()->isEnumeralType()))
246207618Srdivacky      return true;
247207618Srdivacky  } else if (isa<RecordDecl>(SD) ||
248207618Srdivacky             (Context.getLangOptions().CPlusPlus0x && isa<EnumDecl>(SD)))
249221345Sdim    return true;
250221345Sdim
251221345Sdim  return false;
252208599Srdivacky}
253221345Sdim
254221345Sdim/// \brief If the given nested-name-specifier begins with a bare identifier
255221345Sdim/// (e.g., Base::), perform name lookup for that identifier as a
256221345Sdim/// nested-name-specifier within the given scope, and return the result of that
257221345Sdim/// name lookup.
258221345SdimNamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
259221345Sdim  if (!S || !NNS)
260207618Srdivacky    return 0;
261207618Srdivacky
262206083Srdivacky  while (NNS->getPrefix())
263206083Srdivacky    NNS = NNS->getPrefix();
264206124Srdivacky
265207618Srdivacky  if (NNS->getKind() != NestedNameSpecifier::Identifier)
266206083Srdivacky    return 0;
267223017Sdim
268223017Sdim  LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
269223017Sdim                     LookupNestedNameSpecifierName);
270223017Sdim  LookupName(Found, S);
271193323Sed  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
272193323Sed
273193323Sed  if (!Found.isSingleResult())
274193323Sed    return 0;
275193323Sed
276193323Sed  NamedDecl *Result = Found.getFoundDecl();
277193323Sed  if (isAcceptableNestedNameSpecifier(Result))
278193323Sed    return Result;
279193323Sed
280193323Sed  return 0;
281221345Sdim}
282221345Sdim
283221345Sdimbool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
284206274Srdivacky                                        SourceLocation IdLoc,
285206274Srdivacky                                        IdentifierInfo &II,
286206274Srdivacky                                        ParsedType ObjectTypePtr) {
287223017Sdim  QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
288207618Srdivacky  LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
289208599Srdivacky
290208599Srdivacky  // Determine where to perform name lookup
291210299Sed  DeclContext *LookupCtx = 0;
292206274Srdivacky  bool isDependent = false;
293193323Sed  if (!ObjectType.isNull()) {
294199989Srdivacky    // This nested-name-specifier occurs in a member access expression, e.g.,
295193323Sed    // x->B::f, and we are looking into the type of the object.
296199989Srdivacky    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
297193323Sed    LookupCtx = computeDeclContext(ObjectType);
298207618Srdivacky    isDependent = ObjectType->isDependentType();
299208599Srdivacky  } else if (SS.isSet()) {
300193323Sed    // This nested-name-specifier occurs after another nested-name-specifier,
301208599Srdivacky    // so long into the context associated with the prior nested-name-specifier.
302199481Srdivacky    LookupCtx = computeDeclContext(SS, false);
303199481Srdivacky    isDependent = isDependentScopeSpecifier(SS);
304208599Srdivacky    Found.setContextRange(SS.getRange());
305199481Srdivacky  }
306199989Srdivacky
307199989Srdivacky  if (LookupCtx) {
308199989Srdivacky    // Perform "qualified" name lookup into the declaration context we
309199989Srdivacky    // computed, which is either the type of the base of a member access
310208599Srdivacky    // expression or the declaration context associated with a prior
311199481Srdivacky    // nested-name-specifier.
312199989Srdivacky
313199989Srdivacky    // The declaration context must be complete.
314199989Srdivacky    if (!LookupCtx->isDependentContext() &&
315193323Sed        RequireCompleteDeclContext(SS, LookupCtx))
316199989Srdivacky      return false;
317199989Srdivacky
318199989Srdivacky    LookupQualifiedName(Found, LookupCtx);
319199989Srdivacky  } else if (isDependent) {
320199989Srdivacky    return false;
321199989Srdivacky  } else {
322200581Srdivacky    LookupName(Found, S);
323199989Srdivacky  }
324199989Srdivacky  Found.suppressDiagnostics();
325199989Srdivacky
326199989Srdivacky  if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
327206274Srdivacky    return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
328206274Srdivacky
329206274Srdivacky  return false;
330193323Sed}
331199989Srdivacky
332193323Sed/// \brief Build a new nested-name-specifier for "identifier::", as described
333199989Srdivacky/// by ActOnCXXNestedNameSpecifier.
334193323Sed///
335199989Srdivacky/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
336193323Sed/// that it contains an extra parameter \p ScopeLookupResult, which provides
337199989Srdivacky/// the result of name lookup within the scope of the nested-name-specifier
338193323Sed/// that was computed at template definition time.
339199989Srdivacky///
340193323Sed/// If ErrorRecoveryLookup is true, then this call is used to improve error
341199989Srdivacky/// recovery.  This means that it should not emit diagnostics, it should
342193323Sed/// just return null on failure.  It also means it should only return a valid
343200581Srdivacky/// scope if it *knows* that the result is correct.  It should not return in a
344193323Sed/// dependent context, for example.
345199989SrdivackySema::CXXScopeTy *Sema::BuildCXXNestedNameSpecifier(Scope *S,
346193323Sed                                                    CXXScopeSpec &SS,
347199989Srdivacky                                                    SourceLocation IdLoc,
348193323Sed                                                    SourceLocation CCLoc,
349199989Srdivacky                                                    IdentifierInfo &II,
350193323Sed                                                    QualType ObjectType,
351199989Srdivacky                                                  NamedDecl *ScopeLookupResult,
352193323Sed                                                    bool EnteringContext,
353193323Sed                                                    bool ErrorRecoveryLookup) {
354199989Srdivacky  NestedNameSpecifier *Prefix
355193323Sed    = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
356199989Srdivacky
357193323Sed  LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
358199989Srdivacky
359193323Sed  // Determine where to perform name lookup
360199989Srdivacky  DeclContext *LookupCtx = 0;
361193323Sed  bool isDependent = false;
362199989Srdivacky  if (!ObjectType.isNull()) {
363193323Sed    // This nested-name-specifier occurs in a member access expression, e.g.,
364199989Srdivacky    // x->B::f, and we are looking into the type of the object.
365193323Sed    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
366199989Srdivacky    LookupCtx = computeDeclContext(ObjectType);
367193323Sed    isDependent = ObjectType->isDependentType();
368199989Srdivacky  } else if (SS.isSet()) {
369199989Srdivacky    // This nested-name-specifier occurs after another nested-name-specifier,
370199989Srdivacky    // so long into the context associated with the prior nested-name-specifier.
371199989Srdivacky    LookupCtx = computeDeclContext(SS, EnteringContext);
372193323Sed    isDependent = isDependentScopeSpecifier(SS);
373193323Sed    Found.setContextRange(SS.getRange());
374193323Sed  }
375193323Sed
376199989Srdivacky
377193323Sed  bool ObjectTypeSearchedInScope = false;
378199989Srdivacky  if (LookupCtx) {
379193323Sed    // Perform "qualified" name lookup into the declaration context we
380199989Srdivacky    // computed, which is either the type of the base of a member access
381193323Sed    // expression or the declaration context associated with a prior
382199989Srdivacky    // nested-name-specifier.
383193323Sed
384199989Srdivacky    // The declaration context must be complete.
385193323Sed    if (!LookupCtx->isDependentContext() &&
386193323Sed        RequireCompleteDeclContext(SS, LookupCtx))
387193323Sed      return 0;
388193323Sed
389193323Sed    LookupQualifiedName(Found, LookupCtx);
390193323Sed
391193323Sed    if (!ObjectType.isNull() && Found.empty()) {
392193323Sed      // C++ [basic.lookup.classref]p4:
393193323Sed      //   If the id-expression in a class member access is a qualified-id of
394193323Sed      //   the form
395193323Sed      //
396193323Sed      //        class-name-or-namespace-name::...
397193323Sed      //
398193323Sed      //   the class-name-or-namespace-name following the . or -> operator is
399193323Sed      //   looked up both in the context of the entire postfix-expression and in
400193323Sed      //   the scope of the class of the object expression. If the name is found
401193323Sed      //   only in the scope of the class of the object expression, the name
402199989Srdivacky      //   shall refer to a class-name. If the name is found only in the
403193323Sed      //   context of the entire postfix-expression, the name shall refer to a
404208599Srdivacky      //   class-name or namespace-name. [...]
405208599Srdivacky      //
406208599Srdivacky      // Qualified name lookup into a class will not find a namespace-name,
407193323Sed      // so we do not need to diagnoste that case specifically. However,
408208599Srdivacky      // this qualified name lookup may find nothing. In that case, perform
409208599Srdivacky      // unqualified name lookup in the given scope (if available) or
410193323Sed      // reconstruct the result from when name lookup was performed at template
411208599Srdivacky      // definition time.
412208599Srdivacky      if (S)
413193323Sed        LookupName(Found, S);
414208599Srdivacky      else if (ScopeLookupResult)
415208599Srdivacky        Found.addDecl(ScopeLookupResult);
416208599Srdivacky
417204961Srdivacky      ObjectTypeSearchedInScope = true;
418204961Srdivacky    }
419204961Srdivacky  } else if (!isDependent) {
420223017Sdim    // Perform unqualified name lookup in the current scope.
421223017Sdim    LookupName(Found, S);
422206274Srdivacky  }
423208599Srdivacky
424208599Srdivacky  // If we performed lookup into a dependent context and did not find anything,
425208599Srdivacky  // that's fine: just build a dependent nested-name-specifier.
426208599Srdivacky  if (Found.empty() && isDependent &&
427208599Srdivacky      !(LookupCtx && LookupCtx->isRecord() &&
428208599Srdivacky        (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
429208599Srdivacky         !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
430208599Srdivacky    // Don't speculate if we're just trying to improve error recovery.
431208599Srdivacky    if (ErrorRecoveryLookup)
432208599Srdivacky      return 0;
433208599Srdivacky
434207618Srdivacky    // We were not able to compute the declaration context for a dependent
435207618Srdivacky    // base object type or prior nested-name-specifier, so this
436207618Srdivacky    // nested-name-specifier refers to an unknown specialization. Just build
437207618Srdivacky    // a dependent nested-name-specifier.
438199989Srdivacky    if (!Prefix)
439198090Srdivacky      return NestedNameSpecifier::Create(Context, &II);
440203954Srdivacky
441206274Srdivacky    return NestedNameSpecifier::Create(Context, Prefix, &II);
442221345Sdim  }
443221345Sdim
444221345Sdim  // FIXME: Deal with ambiguities cleanly.
445221345Sdim
446221345Sdim  if (Found.empty() && !ErrorRecoveryLookup) {
447199989Srdivacky    // We haven't found anything, and we're not recovering from a
448210299Sed    // different kind of error, so look for typos.
449210299Sed    DeclarationName Name = Found.getLookupName();
450206274Srdivacky    if (CorrectTypo(Found, S, &SS, LookupCtx, EnteringContext,
451208599Srdivacky                    CTC_NoKeywords) &&
452208599Srdivacky        Found.isSingleResult() &&
453208599Srdivacky        isAcceptableNestedNameSpecifier(Found.getAsSingle<NamedDecl>())) {
454208599Srdivacky      if (LookupCtx)
455221345Sdim        Diag(Found.getNameLoc(), diag::err_no_member_suggest)
456221345Sdim          << Name << LookupCtx << Found.getLookupName() << SS.getRange()
457221345Sdim          << FixItHint::CreateReplacement(Found.getNameLoc(),
458221345Sdim                                          Found.getLookupName().getAsString());
459221345Sdim      else
460221345Sdim        Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest)
461221345Sdim          << Name << Found.getLookupName()
462221345Sdim          << FixItHint::CreateReplacement(Found.getNameLoc(),
463221345Sdim                                          Found.getLookupName().getAsString());
464221345Sdim
465221345Sdim      if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
466221345Sdim        Diag(ND->getLocation(), diag::note_previous_decl)
467221345Sdim          << ND->getDeclName();
468221345Sdim    } else {
469221345Sdim      Found.clear();
470221345Sdim      Found.setLookupName(&II);
471221345Sdim    }
472206274Srdivacky  }
473206274Srdivacky
474206274Srdivacky  NamedDecl *SD = Found.getAsSingle<NamedDecl>();
475206274Srdivacky  if (isAcceptableNestedNameSpecifier(SD)) {
476206274Srdivacky    if (!ObjectType.isNull() && !ObjectTypeSearchedInScope) {
477206274Srdivacky      // C++ [basic.lookup.classref]p4:
478198090Srdivacky      //   [...] If the name is found in both contexts, the
479206274Srdivacky      //   class-name-or-namespace-name shall refer to the same entity.
480206274Srdivacky      //
481206274Srdivacky      // We already found the name in the scope of the object. Now, look
482206274Srdivacky      // into the current scope (the scope of the postfix-expression) to
483206274Srdivacky      // see if we can find the same name there. As above, if there is no
484206274Srdivacky      // scope, reconstruct the result from the template instantiation itself.
485206274Srdivacky      NamedDecl *OuterDecl;
486206274Srdivacky      if (S) {
487206274Srdivacky        LookupResult FoundOuter(*this, &II, IdLoc, LookupNestedNameSpecifierName);
488206274Srdivacky        LookupName(FoundOuter, S);
489206274Srdivacky        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
490206274Srdivacky      } else
491206274Srdivacky        OuterDecl = ScopeLookupResult;
492206274Srdivacky
493206274Srdivacky      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
494206274Srdivacky          OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
495218893Sdim          (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
496218893Sdim           !Context.hasSameType(
497199481Srdivacky                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
498218893Sdim                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
499218893Sdim             if (ErrorRecoveryLookup)
500221345Sdim               return 0;
501221345Sdim
502221345Sdim             Diag(IdLoc, diag::err_nested_name_member_ref_lookup_ambiguous)
503221345Sdim               << &II;
504221345Sdim             Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
505221345Sdim               << ObjectType;
506221345Sdim             Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
507221345Sdim
508193323Sed             // Fall through so that we'll pick the name we found in the object
509193323Sed             // type, since that's probably what the user wanted anyway.
510193323Sed           }
511193323Sed    }
512
513    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD))
514      return NestedNameSpecifier::Create(Context, Prefix, Namespace);
515
516    // FIXME: It would be nice to maintain the namespace alias name, then
517    // see through that alias when resolving the nested-name-specifier down to
518    // a declaration context.
519    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD))
520      return NestedNameSpecifier::Create(Context, Prefix,
521
522                                         Alias->getNamespace());
523
524    QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
525    return NestedNameSpecifier::Create(Context, Prefix, false,
526                                       T.getTypePtr());
527  }
528
529  // Otherwise, we have an error case.  If we don't want diagnostics, just
530  // return an error now.
531  if (ErrorRecoveryLookup)
532    return 0;
533
534  // If we didn't find anything during our lookup, try again with
535  // ordinary name lookup, which can help us produce better error
536  // messages.
537  if (Found.empty()) {
538    Found.clear(LookupOrdinaryName);
539    LookupName(Found, S);
540  }
541
542  unsigned DiagID;
543  if (!Found.empty())
544    DiagID = diag::err_expected_class_or_namespace;
545  else if (SS.isSet()) {
546    Diag(IdLoc, diag::err_no_member) << &II << LookupCtx << SS.getRange();
547    return 0;
548  } else
549    DiagID = diag::err_undeclared_var_use;
550
551  if (SS.isSet())
552    Diag(IdLoc, DiagID) << &II << SS.getRange();
553  else
554    Diag(IdLoc, DiagID) << &II;
555
556  return 0;
557}
558
559/// ActOnCXXNestedNameSpecifier - Called during parsing of a
560/// nested-name-specifier. e.g. for "foo::bar::" we parsed "foo::" and now
561/// we want to resolve "bar::". 'SS' is empty or the previously parsed
562/// nested-name part ("foo::"), 'IdLoc' is the source location of 'bar',
563/// 'CCLoc' is the location of '::' and 'II' is the identifier for 'bar'.
564/// Returns a CXXScopeTy* object representing the C++ scope.
565Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
566                                                    CXXScopeSpec &SS,
567                                                    SourceLocation IdLoc,
568                                                    SourceLocation CCLoc,
569                                                    IdentifierInfo &II,
570                                                    ParsedType ObjectTypePtr,
571                                                    bool EnteringContext) {
572  return BuildCXXNestedNameSpecifier(S, SS, IdLoc, CCLoc, II,
573                                     GetTypeFromParser(ObjectTypePtr),
574                                     /*ScopeLookupResult=*/0, EnteringContext,
575                                     false);
576}
577
578/// IsInvalidUnlessNestedName - This method is used for error recovery
579/// purposes to determine whether the specified identifier is only valid as
580/// a nested name specifier, for example a namespace name.  It is
581/// conservatively correct to always return false from this method.
582///
583/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
584bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
585                                     IdentifierInfo &II, ParsedType ObjectType,
586                                     bool EnteringContext) {
587  return BuildCXXNestedNameSpecifier(S, SS, SourceLocation(), SourceLocation(),
588                                     II, GetTypeFromParser(ObjectType),
589                                     /*ScopeLookupResult=*/0, EnteringContext,
590                                     true);
591}
592
593Sema::CXXScopeTy *Sema::ActOnCXXNestedNameSpecifier(Scope *S,
594                                                    const CXXScopeSpec &SS,
595                                                    ParsedType Ty,
596                                                    SourceRange TypeRange,
597                                                    SourceLocation CCLoc) {
598  NestedNameSpecifier *Prefix = SS.getScopeRep();
599  QualType T = GetTypeFromParser(Ty);
600  return NestedNameSpecifier::Create(Context, Prefix, /*FIXME:*/false,
601                                     T.getTypePtr());
602}
603
604bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
605  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
606
607  NestedNameSpecifier *Qualifier =
608    static_cast<NestedNameSpecifier*>(SS.getScopeRep());
609
610  // There are only two places a well-formed program may qualify a
611  // declarator: first, when defining a namespace or class member
612  // out-of-line, and second, when naming an explicitly-qualified
613  // friend function.  The latter case is governed by
614  // C++03 [basic.lookup.unqual]p10:
615  //   In a friend declaration naming a member function, a name used
616  //   in the function declarator and not part of a template-argument
617  //   in a template-id is first looked up in the scope of the member
618  //   function's class. If it is not found, or if the name is part of
619  //   a template-argument in a template-id, the look up is as
620  //   described for unqualified names in the definition of the class
621  //   granting friendship.
622  // i.e. we don't push a scope unless it's a class member.
623
624  switch (Qualifier->getKind()) {
625  case NestedNameSpecifier::Global:
626  case NestedNameSpecifier::Namespace:
627    // These are always namespace scopes.  We never want to enter a
628    // namespace scope from anything but a file context.
629    return CurContext->getRedeclContext()->isFileContext();
630
631  case NestedNameSpecifier::Identifier:
632  case NestedNameSpecifier::TypeSpec:
633  case NestedNameSpecifier::TypeSpecWithTemplate:
634    // These are never namespace scopes.
635    return true;
636  }
637
638  // Silence bogus warning.
639  return false;
640}
641
642/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
643/// scope or nested-name-specifier) is parsed, part of a declarator-id.
644/// After this method is called, according to [C++ 3.4.3p3], names should be
645/// looked up in the declarator-id's scope, until the declarator is parsed and
646/// ActOnCXXExitDeclaratorScope is called.
647/// The 'SS' should be a non-empty valid CXXScopeSpec.
648bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
649  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
650
651  if (SS.isInvalid()) return true;
652
653  DeclContext *DC = computeDeclContext(SS, true);
654  if (!DC) return true;
655
656  // Before we enter a declarator's context, we need to make sure that
657  // it is a complete declaration context.
658  if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
659    return true;
660
661  EnterDeclaratorContext(S, DC);
662
663  // Rebuild the nested name specifier for the new scope.
664  if (DC->isDependentContext())
665    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
666
667  return false;
668}
669
670/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
671/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
672/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
673/// Used to indicate that names should revert to being looked up in the
674/// defining scope.
675void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
676  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
677  if (SS.isInvalid())
678    return;
679  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
680         "exiting declarator scope we never really entered");
681  ExitDeclaratorContext(S);
682}
683