1193326Sed//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements C++ semantic analysis for scope specifiers.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14212904Sdim#include "clang/Sema/SemaInternal.h"
15252723Sdim#include "TypeLocBuilder.h"
16193326Sed#include "clang/AST/ASTContext.h"
17193326Sed#include "clang/AST/DeclTemplate.h"
18198092Srdivacky#include "clang/AST/ExprCXX.h"
19193326Sed#include "clang/AST/NestedNameSpecifier.h"
20198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
21212904Sdim#include "clang/Sema/DeclSpec.h"
22252723Sdim#include "clang/Sema/Lookup.h"
23252723Sdim#include "clang/Sema/Template.h"
24193326Sed#include "llvm/ADT/STLExtras.h"
25198092Srdivacky#include "llvm/Support/raw_ostream.h"
26193326Sedusing namespace clang;
27193326Sed
28198954Srdivacky/// \brief Find the current instantiation that associated with the given type.
29252723Sdimstatic CXXRecordDecl *getCurrentInstantiationOf(QualType T,
30218893Sdim                                                DeclContext *CurContext) {
31198954Srdivacky  if (T.isNull())
32198954Srdivacky    return 0;
33207619Srdivacky
34207619Srdivacky  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
35218893Sdim  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
36218893Sdim    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
37252723Sdim    if (!Record->isDependentContext() ||
38252723Sdim        Record->isCurrentInstantiation(CurContext))
39218893Sdim      return Record;
40218893Sdim
41218893Sdim    return 0;
42218893Sdim  } else if (isa<InjectedClassNameType>(Ty))
43207619Srdivacky    return cast<InjectedClassNameType>(Ty)->getDecl();
44207619Srdivacky  else
45207619Srdivacky    return 0;
46198954Srdivacky}
47198954Srdivacky
48198092Srdivacky/// \brief Compute the DeclContext that is associated with the given type.
49198092Srdivacky///
50198092Srdivacky/// \param T the type for which we are attempting to find a DeclContext.
51198092Srdivacky///
52198092Srdivacky/// \returns the declaration context represented by the type T,
53198092Srdivacky/// or NULL if the declaration context cannot be computed (e.g., because it is
54198092Srdivacky/// dependent and not the current instantiation).
55198092SrdivackyDeclContext *Sema::computeDeclContext(QualType T) {
56218893Sdim  if (!T->isDependentType())
57218893Sdim    if (const TagType *Tag = T->getAs<TagType>())
58218893Sdim      return Tag->getDecl();
59198092Srdivacky
60218893Sdim  return ::getCurrentInstantiationOf(T, CurContext);
61198092Srdivacky}
62198092Srdivacky
63193326Sed/// \brief Compute the DeclContext that is associated with the given
64193326Sed/// scope specifier.
65198092Srdivacky///
66198092Srdivacky/// \param SS the C++ scope specifier as it appears in the source
67198092Srdivacky///
68198092Srdivacky/// \param EnteringContext when true, we will be entering the context of
69198092Srdivacky/// this scope specifier, so we can retrieve the declaration context of a
70198092Srdivacky/// class template or class template partial specialization even if it is
71198092Srdivacky/// not the current instantiation.
72198092Srdivacky///
73198092Srdivacky/// \returns the declaration context represented by the scope specifier @p SS,
74198092Srdivacky/// or NULL if the declaration context cannot be computed (e.g., because it is
75198092Srdivacky/// dependent and not the current instantiation).
76198092SrdivackyDeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
77198092Srdivacky                                      bool EnteringContext) {
78193326Sed  if (!SS.isSet() || SS.isInvalid())
79193326Sed    return 0;
80193326Sed
81252723Sdim  NestedNameSpecifier *NNS = SS.getScopeRep();
82193326Sed  if (NNS->isDependent()) {
83193326Sed    // If this nested-name-specifier refers to the current
84193326Sed    // instantiation, return its DeclContext.
85193326Sed    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
86193326Sed      return Record;
87198092Srdivacky
88198092Srdivacky    if (EnteringContext) {
89204962Srdivacky      const Type *NNSType = NNS->getAsType();
90204962Srdivacky      if (!NNSType) {
91223017Sdim        return 0;
92223017Sdim      }
93223017Sdim
94223017Sdim      // Look through type alias templates, per C++0x [temp.dep.type]p1.
95223017Sdim      NNSType = Context.getCanonicalType(NNSType);
96223017Sdim      if (const TemplateSpecializationType *SpecType
97223017Sdim            = NNSType->getAs<TemplateSpecializationType>()) {
98198092Srdivacky        // We are entering the context of the nested name specifier, so try to
99198092Srdivacky        // match the nested name specifier to either a primary class template
100198092Srdivacky        // or a class template partial specialization.
101198092Srdivacky        if (ClassTemplateDecl *ClassTemplate
102198092Srdivacky              = dyn_cast_or_null<ClassTemplateDecl>(
103198092Srdivacky                            SpecType->getTemplateName().getAsTemplateDecl())) {
104198092Srdivacky          QualType ContextType
105198092Srdivacky            = Context.getCanonicalType(QualType(SpecType, 0));
106198092Srdivacky
107198092Srdivacky          // If the type of the nested name specifier is the same as the
108198092Srdivacky          // injected class name of the named class template, we're entering
109198092Srdivacky          // into that class template definition.
110204962Srdivacky          QualType Injected
111210299Sed            = ClassTemplate->getInjectedClassNameSpecialization();
112198092Srdivacky          if (Context.hasSameType(Injected, ContextType))
113198092Srdivacky            return ClassTemplate->getTemplatedDecl();
114198092Srdivacky
115198092Srdivacky          // If the type of the nested name specifier is the same as the
116198092Srdivacky          // type of one of the class template's class template partial
117198092Srdivacky          // specializations, we're entering into the definition of that
118198092Srdivacky          // class template partial specialization.
119198092Srdivacky          if (ClassTemplatePartialSpecializationDecl *PartialSpec
120198092Srdivacky                = ClassTemplate->findPartialSpecialization(ContextType))
121198092Srdivacky            return PartialSpec;
122198092Srdivacky        }
123204962Srdivacky      } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
124198092Srdivacky        // The nested name specifier refers to a member of a class template.
125198092Srdivacky        return RecordT->getDecl();
126198092Srdivacky      }
127198092Srdivacky    }
128198092Srdivacky
129198092Srdivacky    return 0;
130193326Sed  }
131193326Sed
132193326Sed  switch (NNS->getKind()) {
133193326Sed  case NestedNameSpecifier::Identifier:
134226890Sdim    llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
135193326Sed
136193326Sed  case NestedNameSpecifier::Namespace:
137193326Sed    return NNS->getAsNamespace();
138193326Sed
139219077Sdim  case NestedNameSpecifier::NamespaceAlias:
140219077Sdim    return NNS->getAsNamespaceAlias()->getNamespace();
141219077Sdim
142193326Sed  case NestedNameSpecifier::TypeSpec:
143193326Sed  case NestedNameSpecifier::TypeSpecWithTemplate: {
144198092Srdivacky    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
145193326Sed    assert(Tag && "Non-tag type in nested-name-specifier");
146193326Sed    return Tag->getDecl();
147235633Sdim  }
148193326Sed
149193326Sed  case NestedNameSpecifier::Global:
150193326Sed    return Context.getTranslationUnitDecl();
151193326Sed  }
152193326Sed
153235633Sdim  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
154193326Sed}
155193326Sed
156193326Sedbool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
157193326Sed  if (!SS.isSet() || SS.isInvalid())
158193326Sed    return false;
159193326Sed
160252723Sdim  return SS.getScopeRep()->isDependent();
161193326Sed}
162193326Sed
163193326Sed/// \brief If the given nested name specifier refers to the current
164193326Sed/// instantiation, return the declaration that corresponds to that
165193326Sed/// current instantiation (C++0x [temp.dep.type]p1).
166193326Sed///
167193326Sed/// \param NNS a dependent nested name specifier.
168193326SedCXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
169235633Sdim  assert(getLangOpts().CPlusPlus && "Only callable in C++");
170193326Sed  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
171193326Sed
172198092Srdivacky  if (!NNS->getAsType())
173198092Srdivacky    return 0;
174198092Srdivacky
175193326Sed  QualType T = QualType(NNS->getAsType(), 0);
176218893Sdim  return ::getCurrentInstantiationOf(T, CurContext);
177193326Sed}
178193326Sed
179193326Sed/// \brief Require that the context specified by SS be complete.
180193326Sed///
181193326Sed/// If SS refers to a type, this routine checks whether the type is
182193326Sed/// complete enough (or can be made complete enough) for name lookup
183193326Sed/// into the DeclContext. A type that is not yet completed can be
184193326Sed/// considered "complete enough" if it is a class/struct/union/enum
185193326Sed/// that is currently being defined. Or, if we have a type that names
186193326Sed/// a class template specialization that is not a complete type, we
187193326Sed/// will attempt to instantiate that class template.
188207619Srdivackybool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
189207619Srdivacky                                      DeclContext *DC) {
190207619Srdivacky  assert(DC != 0 && "given null context");
191198092Srdivacky
192235633Sdim  TagDecl *tag = dyn_cast<TagDecl>(DC);
193203955Srdivacky
194235633Sdim  // If this is a dependent type, then we consider it complete.
195235633Sdim  if (!tag || tag->isDependentContext())
196235633Sdim    return false;
197193326Sed
198235633Sdim  // If we're currently defining this type, then lookup into the
199235633Sdim  // type is okay: don't complain that it isn't complete yet.
200235633Sdim  QualType type = Context.getTypeDeclType(tag);
201235633Sdim  const TagType *tagType = type->getAs<TagType>();
202235633Sdim  if (tagType && tagType->isBeingDefined())
203235633Sdim    return false;
204224145Sdim
205235633Sdim  SourceLocation loc = SS.getLastQualifierNameLoc();
206235633Sdim  if (loc.isInvalid()) loc = SS.getRange().getBegin();
207224145Sdim
208235633Sdim  // The type must be complete.
209245431Sdim  if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
210245431Sdim                          SS.getRange())) {
211235633Sdim    SS.SetInvalid(SS.getRange());
212235633Sdim    return true;
213235633Sdim  }
214235633Sdim
215235633Sdim  // Fixed enum types are complete, but they aren't valid as scopes
216235633Sdim  // until we see a definition, so awkwardly pull out this special
217235633Sdim  // case.
218235633Sdim  const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType);
219235633Sdim  if (!enumType || enumType->getDecl()->isCompleteDefinition())
220235633Sdim    return false;
221235633Sdim
222235633Sdim  // Try to instantiate the definition, if this is a specialization of an
223235633Sdim  // enumeration temploid.
224235633Sdim  EnumDecl *ED = enumType->getDecl();
225235633Sdim  if (EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
226235633Sdim    MemberSpecializationInfo *MSI = ED->getMemberSpecializationInfo();
227235633Sdim    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
228235633Sdim      if (InstantiateEnum(loc, ED, Pattern, getTemplateInstantiationArgs(ED),
229235633Sdim                          TSK_ImplicitInstantiation)) {
230224145Sdim        SS.SetInvalid(SS.getRange());
231224145Sdim        return true;
232224145Sdim      }
233235633Sdim      return false;
234224145Sdim    }
235193326Sed  }
236193326Sed
237235633Sdim  Diag(loc, diag::err_incomplete_nested_name_spec)
238235633Sdim    << type << SS.getRange();
239235633Sdim  SS.SetInvalid(SS.getRange());
240235633Sdim  return true;
241193326Sed}
242193326Sed
243219077Sdimbool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
244219077Sdim                                        CXXScopeSpec &SS) {
245219077Sdim  SS.MakeGlobal(Context, CCLoc);
246219077Sdim  return false;
247193326Sed}
248193326Sed
249198092Srdivacky/// \brief Determines whether the given declaration is an valid acceptable
250198092Srdivacky/// result for name lookup of a nested-name-specifier.
251252723Sdimbool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD) {
252198092Srdivacky  if (!SD)
253198092Srdivacky    return false;
254198092Srdivacky
255198092Srdivacky  // Namespace and namespace aliases are fine.
256198092Srdivacky  if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
257198092Srdivacky    return true;
258198092Srdivacky
259198092Srdivacky  if (!isa<TypeDecl>(SD))
260198092Srdivacky    return false;
261198092Srdivacky
262235633Sdim  // Determine whether we have a class (or, in C++11, an enum) or
263198092Srdivacky  // a typedef thereof. If so, build the nested-name-specifier.
264198092Srdivacky  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
265198092Srdivacky  if (T->isDependentType())
266198092Srdivacky    return true;
267252723Sdim  else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
268198092Srdivacky    if (TD->getUnderlyingType()->isRecordType() ||
269252723Sdim        (Context.getLangOpts().CPlusPlus11 &&
270198092Srdivacky         TD->getUnderlyingType()->isEnumeralType()))
271198092Srdivacky      return true;
272198092Srdivacky  } else if (isa<RecordDecl>(SD) ||
273252723Sdim             (Context.getLangOpts().CPlusPlus11 && isa<EnumDecl>(SD)))
274198092Srdivacky    return true;
275198092Srdivacky
276198092Srdivacky  return false;
277198092Srdivacky}
278198092Srdivacky
279198092Srdivacky/// \brief If the given nested-name-specifier begins with a bare identifier
280198092Srdivacky/// (e.g., Base::), perform name lookup for that identifier as a
281198092Srdivacky/// nested-name-specifier within the given scope, and return the result of that
282198092Srdivacky/// name lookup.
283198092SrdivackyNamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
284198092Srdivacky  if (!S || !NNS)
285198092Srdivacky    return 0;
286198092Srdivacky
287198092Srdivacky  while (NNS->getPrefix())
288198092Srdivacky    NNS = NNS->getPrefix();
289198092Srdivacky
290198092Srdivacky  if (NNS->getKind() != NestedNameSpecifier::Identifier)
291198092Srdivacky    return 0;
292198092Srdivacky
293199482Srdivacky  LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
294199482Srdivacky                     LookupNestedNameSpecifierName);
295199482Srdivacky  LookupName(Found, S);
296198092Srdivacky  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
297198092Srdivacky
298200583Srdivacky  if (!Found.isSingleResult())
299200583Srdivacky    return 0;
300200583Srdivacky
301200583Srdivacky  NamedDecl *Result = Found.getFoundDecl();
302198092Srdivacky  if (isAcceptableNestedNameSpecifier(Result))
303198092Srdivacky    return Result;
304198092Srdivacky
305198092Srdivacky  return 0;
306198092Srdivacky}
307198092Srdivacky
308207619Srdivackybool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
309204643Srdivacky                                        SourceLocation IdLoc,
310204643Srdivacky                                        IdentifierInfo &II,
311212904Sdim                                        ParsedType ObjectTypePtr) {
312204643Srdivacky  QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
313204643Srdivacky  LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
314204643Srdivacky
315204643Srdivacky  // Determine where to perform name lookup
316204643Srdivacky  DeclContext *LookupCtx = 0;
317204643Srdivacky  bool isDependent = false;
318204643Srdivacky  if (!ObjectType.isNull()) {
319204643Srdivacky    // This nested-name-specifier occurs in a member access expression, e.g.,
320204643Srdivacky    // x->B::f, and we are looking into the type of the object.
321204643Srdivacky    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
322204643Srdivacky    LookupCtx = computeDeclContext(ObjectType);
323204643Srdivacky    isDependent = ObjectType->isDependentType();
324204643Srdivacky  } else if (SS.isSet()) {
325204643Srdivacky    // This nested-name-specifier occurs after another nested-name-specifier,
326204643Srdivacky    // so long into the context associated with the prior nested-name-specifier.
327204643Srdivacky    LookupCtx = computeDeclContext(SS, false);
328204643Srdivacky    isDependent = isDependentScopeSpecifier(SS);
329204643Srdivacky    Found.setContextRange(SS.getRange());
330204643Srdivacky  }
331204643Srdivacky
332204643Srdivacky  if (LookupCtx) {
333204643Srdivacky    // Perform "qualified" name lookup into the declaration context we
334204643Srdivacky    // computed, which is either the type of the base of a member access
335204643Srdivacky    // expression or the declaration context associated with a prior
336204643Srdivacky    // nested-name-specifier.
337204643Srdivacky
338204643Srdivacky    // The declaration context must be complete.
339207619Srdivacky    if (!LookupCtx->isDependentContext() &&
340207619Srdivacky        RequireCompleteDeclContext(SS, LookupCtx))
341204643Srdivacky      return false;
342204643Srdivacky
343204643Srdivacky    LookupQualifiedName(Found, LookupCtx);
344204643Srdivacky  } else if (isDependent) {
345204643Srdivacky    return false;
346204643Srdivacky  } else {
347204643Srdivacky    LookupName(Found, S);
348204643Srdivacky  }
349204643Srdivacky  Found.suppressDiagnostics();
350204643Srdivacky
351204643Srdivacky  if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
352204643Srdivacky    return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
353204643Srdivacky
354204643Srdivacky  return false;
355204643Srdivacky}
356204643Srdivacky
357235633Sdimnamespace {
358235633Sdim
359235633Sdim// Callback to only accept typo corrections that can be a valid C++ member
360235633Sdim// intializer: either a non-static field member or a base class.
361235633Sdimclass NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback {
362235633Sdim public:
363235633Sdim  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
364235633Sdim      : SRef(SRef) {}
365235633Sdim
366235633Sdim  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
367235633Sdim    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
368235633Sdim  }
369235633Sdim
370235633Sdim private:
371235633Sdim  Sema &SRef;
372235633Sdim};
373235633Sdim
374235633Sdim}
375235633Sdim
376198092Srdivacky/// \brief Build a new nested-name-specifier for "identifier::", as described
377198092Srdivacky/// by ActOnCXXNestedNameSpecifier.
378198092Srdivacky///
379198092Srdivacky/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
380198092Srdivacky/// that it contains an extra parameter \p ScopeLookupResult, which provides
381198092Srdivacky/// the result of name lookup within the scope of the nested-name-specifier
382201361Srdivacky/// that was computed at template definition time.
383200583Srdivacky///
384200583Srdivacky/// If ErrorRecoveryLookup is true, then this call is used to improve error
385200583Srdivacky/// recovery.  This means that it should not emit diagnostics, it should
386219077Sdim/// just return true on failure.  It also means it should only return a valid
387200583Srdivacky/// scope if it *knows* that the result is correct.  It should not return in a
388219077Sdim/// dependent context, for example. Nor will it extend \p SS with the scope
389219077Sdim/// specifier.
390219077Sdimbool Sema::BuildCXXNestedNameSpecifier(Scope *S,
391219077Sdim                                       IdentifierInfo &Identifier,
392219077Sdim                                       SourceLocation IdentifierLoc,
393219077Sdim                                       SourceLocation CCLoc,
394219077Sdim                                       QualType ObjectType,
395219077Sdim                                       bool EnteringContext,
396219077Sdim                                       CXXScopeSpec &SS,
397219077Sdim                                       NamedDecl *ScopeLookupResult,
398219077Sdim                                       bool ErrorRecoveryLookup) {
399219077Sdim  LookupResult Found(*this, &Identifier, IdentifierLoc,
400219077Sdim                     LookupNestedNameSpecifierName);
401193326Sed
402198092Srdivacky  // Determine where to perform name lookup
403198092Srdivacky  DeclContext *LookupCtx = 0;
404198092Srdivacky  bool isDependent = false;
405198092Srdivacky  if (!ObjectType.isNull()) {
406198092Srdivacky    // This nested-name-specifier occurs in a member access expression, e.g.,
407198092Srdivacky    // x->B::f, and we are looking into the type of the object.
408198092Srdivacky    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
409198092Srdivacky    LookupCtx = computeDeclContext(ObjectType);
410198092Srdivacky    isDependent = ObjectType->isDependentType();
411198092Srdivacky  } else if (SS.isSet()) {
412198092Srdivacky    // This nested-name-specifier occurs after another nested-name-specifier,
413223017Sdim    // so look into the context associated with the prior nested-name-specifier.
414198092Srdivacky    LookupCtx = computeDeclContext(SS, EnteringContext);
415198092Srdivacky    isDependent = isDependentScopeSpecifier(SS);
416199482Srdivacky    Found.setContextRange(SS.getRange());
417198092Srdivacky  }
418198092Srdivacky
419199482Srdivacky
420198092Srdivacky  bool ObjectTypeSearchedInScope = false;
421198092Srdivacky  if (LookupCtx) {
422198092Srdivacky    // Perform "qualified" name lookup into the declaration context we
423198092Srdivacky    // computed, which is either the type of the base of a member access
424198092Srdivacky    // expression or the declaration context associated with a prior
425198092Srdivacky    // nested-name-specifier.
426198092Srdivacky
427198092Srdivacky    // The declaration context must be complete.
428207619Srdivacky    if (!LookupCtx->isDependentContext() &&
429207619Srdivacky        RequireCompleteDeclContext(SS, LookupCtx))
430219077Sdim      return true;
431198092Srdivacky
432199482Srdivacky    LookupQualifiedName(Found, LookupCtx);
433198092Srdivacky
434199482Srdivacky    if (!ObjectType.isNull() && Found.empty()) {
435198092Srdivacky      // C++ [basic.lookup.classref]p4:
436198092Srdivacky      //   If the id-expression in a class member access is a qualified-id of
437198092Srdivacky      //   the form
438198092Srdivacky      //
439198092Srdivacky      //        class-name-or-namespace-name::...
440198092Srdivacky      //
441198092Srdivacky      //   the class-name-or-namespace-name following the . or -> operator is
442198092Srdivacky      //   looked up both in the context of the entire postfix-expression and in
443198092Srdivacky      //   the scope of the class of the object expression. If the name is found
444198092Srdivacky      //   only in the scope of the class of the object expression, the name
445198092Srdivacky      //   shall refer to a class-name. If the name is found only in the
446198092Srdivacky      //   context of the entire postfix-expression, the name shall refer to a
447198092Srdivacky      //   class-name or namespace-name. [...]
448198092Srdivacky      //
449198092Srdivacky      // Qualified name lookup into a class will not find a namespace-name,
450223017Sdim      // so we do not need to diagnose that case specifically. However,
451198092Srdivacky      // this qualified name lookup may find nothing. In that case, perform
452198092Srdivacky      // unqualified name lookup in the given scope (if available) or
453198092Srdivacky      // reconstruct the result from when name lookup was performed at template
454198092Srdivacky      // definition time.
455198092Srdivacky      if (S)
456199482Srdivacky        LookupName(Found, S);
457198092Srdivacky      else if (ScopeLookupResult)
458198092Srdivacky        Found.addDecl(ScopeLookupResult);
459198092Srdivacky
460198092Srdivacky      ObjectTypeSearchedInScope = true;
461198092Srdivacky    }
462212904Sdim  } else if (!isDependent) {
463212904Sdim    // Perform unqualified name lookup in the current scope.
464212904Sdim    LookupName(Found, S);
465212904Sdim  }
466212904Sdim
467212904Sdim  // If we performed lookup into a dependent context and did not find anything,
468212904Sdim  // that's fine: just build a dependent nested-name-specifier.
469212904Sdim  if (Found.empty() && isDependent &&
470212904Sdim      !(LookupCtx && LookupCtx->isRecord() &&
471212904Sdim        (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
472212904Sdim         !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
473200583Srdivacky    // Don't speculate if we're just trying to improve error recovery.
474200583Srdivacky    if (ErrorRecoveryLookup)
475219077Sdim      return true;
476200583Srdivacky
477198092Srdivacky    // We were not able to compute the declaration context for a dependent
478198092Srdivacky    // base object type or prior nested-name-specifier, so this
479198092Srdivacky    // nested-name-specifier refers to an unknown specialization. Just build
480198092Srdivacky    // a dependent nested-name-specifier.
481219077Sdim    SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
482219077Sdim    return false;
483212904Sdim  }
484212904Sdim
485198092Srdivacky  // FIXME: Deal with ambiguities cleanly.
486201361Srdivacky
487263509Sdim  if (Found.empty() && !ErrorRecoveryLookup && !getLangOpts().MicrosoftMode) {
488201361Srdivacky    // We haven't found anything, and we're not recovering from a
489201361Srdivacky    // different kind of error, so look for typos.
490201361Srdivacky    DeclarationName Name = Found.getLookupName();
491235633Sdim    NestedNameSpecifierValidatorCCC Validator(*this);
492224145Sdim    Found.clear();
493263509Sdim    if (TypoCorrection Corrected =
494263509Sdim            CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
495263509Sdim                        &SS, Validator, LookupCtx, EnteringContext)) {
496263509Sdim      if (LookupCtx) {
497263509Sdim        bool DroppedSpecifier =
498263509Sdim            Corrected.WillReplaceSpecifier() &&
499263509Sdim            Name.getAsString() == Corrected.getAsString(getLangOpts());
500263509Sdim        if (DroppedSpecifier)
501263509Sdim          SS.clear();
502263509Sdim        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
503263509Sdim                                  << Name << LookupCtx << DroppedSpecifier
504263509Sdim                                  << SS.getRange());
505263509Sdim      } else
506263509Sdim        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
507263509Sdim                                  << Name);
508263509Sdim
509263509Sdim      if (NamedDecl *ND = Corrected.getCorrectionDecl())
510224145Sdim        Found.addDecl(ND);
511224145Sdim      Found.setLookupName(Corrected.getCorrection());
512210299Sed    } else {
513219077Sdim      Found.setLookupName(&Identifier);
514210299Sed    }
515201361Srdivacky  }
516201361Srdivacky
517200583Srdivacky  NamedDecl *SD = Found.getAsSingle<NamedDecl>();
518198092Srdivacky  if (isAcceptableNestedNameSpecifier(SD)) {
519245431Sdim    if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
520252723Sdim        !getLangOpts().CPlusPlus11) {
521245431Sdim      // C++03 [basic.lookup.classref]p4:
522198092Srdivacky      //   [...] If the name is found in both contexts, the
523198092Srdivacky      //   class-name-or-namespace-name shall refer to the same entity.
524198092Srdivacky      //
525198092Srdivacky      // We already found the name in the scope of the object. Now, look
526198092Srdivacky      // into the current scope (the scope of the postfix-expression) to
527198092Srdivacky      // see if we can find the same name there. As above, if there is no
528198092Srdivacky      // scope, reconstruct the result from the template instantiation itself.
529245431Sdim      //
530245431Sdim      // Note that C++11 does *not* perform this redundant lookup.
531198092Srdivacky      NamedDecl *OuterDecl;
532198092Srdivacky      if (S) {
533219077Sdim        LookupResult FoundOuter(*this, &Identifier, IdentifierLoc,
534219077Sdim                                LookupNestedNameSpecifierName);
535199482Srdivacky        LookupName(FoundOuter, S);
536200583Srdivacky        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
537198092Srdivacky      } else
538198092Srdivacky        OuterDecl = ScopeLookupResult;
539193326Sed
540198092Srdivacky      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
541198092Srdivacky          OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
542198092Srdivacky          (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
543198092Srdivacky           !Context.hasSameType(
544198092Srdivacky                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
545198092Srdivacky                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
546219077Sdim         if (ErrorRecoveryLookup)
547219077Sdim           return true;
548198092Srdivacky
549219077Sdim         Diag(IdentifierLoc,
550219077Sdim              diag::err_nested_name_member_ref_lookup_ambiguous)
551219077Sdim           << &Identifier;
552219077Sdim         Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
553219077Sdim           << ObjectType;
554219077Sdim         Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
555219077Sdim
556219077Sdim         // Fall through so that we'll pick the name we found in the object
557219077Sdim         // type, since that's probably what the user wanted anyway.
558219077Sdim       }
559198092Srdivacky    }
560198092Srdivacky
561219077Sdim    // If we're just performing this lookup for error-recovery purposes,
562219077Sdim    // don't extend the nested-name-specifier. Just return now.
563219077Sdim    if (ErrorRecoveryLookup)
564219077Sdim      return false;
565219077Sdim
566219077Sdim    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
567219077Sdim      SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
568219077Sdim      return false;
569219077Sdim    }
570193326Sed
571219077Sdim    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
572219077Sdim      SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
573219077Sdim      return false;
574219077Sdim    }
575193326Sed
576198092Srdivacky    QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
577219077Sdim    TypeLocBuilder TLB;
578219077Sdim    if (isa<InjectedClassNameType>(T)) {
579219077Sdim      InjectedClassNameTypeLoc InjectedTL
580219077Sdim        = TLB.push<InjectedClassNameTypeLoc>(T);
581219077Sdim      InjectedTL.setNameLoc(IdentifierLoc);
582223017Sdim    } else if (isa<RecordType>(T)) {
583219077Sdim      RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
584219077Sdim      RecordTL.setNameLoc(IdentifierLoc);
585223017Sdim    } else if (isa<TypedefType>(T)) {
586219077Sdim      TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
587219077Sdim      TypedefTL.setNameLoc(IdentifierLoc);
588223017Sdim    } else if (isa<EnumType>(T)) {
589219077Sdim      EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
590219077Sdim      EnumTL.setNameLoc(IdentifierLoc);
591223017Sdim    } else if (isa<TemplateTypeParmType>(T)) {
592219077Sdim      TemplateTypeParmTypeLoc TemplateTypeTL
593219077Sdim        = TLB.push<TemplateTypeParmTypeLoc>(T);
594219077Sdim      TemplateTypeTL.setNameLoc(IdentifierLoc);
595223017Sdim    } else if (isa<UnresolvedUsingType>(T)) {
596219077Sdim      UnresolvedUsingTypeLoc UnresolvedTL
597219077Sdim        = TLB.push<UnresolvedUsingTypeLoc>(T);
598219077Sdim      UnresolvedTL.setNameLoc(IdentifierLoc);
599223017Sdim    } else if (isa<SubstTemplateTypeParmType>(T)) {
600223017Sdim      SubstTemplateTypeParmTypeLoc TL
601223017Sdim        = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
602223017Sdim      TL.setNameLoc(IdentifierLoc);
603223017Sdim    } else if (isa<SubstTemplateTypeParmPackType>(T)) {
604223017Sdim      SubstTemplateTypeParmPackTypeLoc TL
605223017Sdim        = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
606223017Sdim      TL.setNameLoc(IdentifierLoc);
607223017Sdim    } else {
608223017Sdim      llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
609219077Sdim    }
610219077Sdim
611235633Sdim    if (T->isEnumeralType())
612235633Sdim      Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
613235633Sdim
614219077Sdim    SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
615219077Sdim              CCLoc);
616219077Sdim    return false;
617193326Sed  }
618193326Sed
619200583Srdivacky  // Otherwise, we have an error case.  If we don't want diagnostics, just
620200583Srdivacky  // return an error now.
621200583Srdivacky  if (ErrorRecoveryLookup)
622219077Sdim    return true;
623200583Srdivacky
624193326Sed  // If we didn't find anything during our lookup, try again with
625193326Sed  // ordinary name lookup, which can help us produce better error
626193326Sed  // messages.
627200583Srdivacky  if (Found.empty()) {
628199482Srdivacky    Found.clear(LookupOrdinaryName);
629199482Srdivacky    LookupName(Found, S);
630198092Srdivacky  }
631198092Srdivacky
632226890Sdim  // In Microsoft mode, if we are within a templated function and we can't
633226890Sdim  // resolve Identifier, then extend the SS with Identifier. This will have
634226890Sdim  // the effect of resolving Identifier during template instantiation.
635226890Sdim  // The goal is to be able to resolve a function call whose
636226890Sdim  // nested-name-specifier is located inside a dependent base class.
637226890Sdim  // Example:
638226890Sdim  //
639226890Sdim  // class C {
640226890Sdim  // public:
641226890Sdim  //    static void foo2() {  }
642226890Sdim  // };
643226890Sdim  // template <class T> class A { public: typedef C D; };
644226890Sdim  //
645226890Sdim  // template <class T> class B : public A<T> {
646226890Sdim  // public:
647226890Sdim  //   void foo() { D::foo2(); }
648226890Sdim  // };
649263509Sdim  if (getLangOpts().MicrosoftMode) {
650226890Sdim    DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
651226890Sdim    if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
652226890Sdim      SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
653226890Sdim      return false;
654226890Sdim    }
655226890Sdim  }
656226890Sdim
657193326Sed  unsigned DiagID;
658200583Srdivacky  if (!Found.empty())
659193326Sed    DiagID = diag::err_expected_class_or_namespace;
660198092Srdivacky  else if (SS.isSet()) {
661219077Sdim    Diag(IdentifierLoc, diag::err_no_member)
662219077Sdim      << &Identifier << LookupCtx << SS.getRange();
663219077Sdim    return true;
664198092Srdivacky  } else
665193326Sed    DiagID = diag::err_undeclared_var_use;
666193326Sed
667193326Sed  if (SS.isSet())
668219077Sdim    Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange();
669193326Sed  else
670219077Sdim    Diag(IdentifierLoc, DiagID) << &Identifier;
671193326Sed
672219077Sdim  return true;
673193326Sed}
674193326Sed
675219077Sdimbool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
676219077Sdim                                       IdentifierInfo &Identifier,
677219077Sdim                                       SourceLocation IdentifierLoc,
678219077Sdim                                       SourceLocation CCLoc,
679219077Sdim                                       ParsedType ObjectType,
680219077Sdim                                       bool EnteringContext,
681219077Sdim                                       CXXScopeSpec &SS) {
682219077Sdim  if (SS.isInvalid())
683219077Sdim    return true;
684219077Sdim
685219077Sdim  return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
686219077Sdim                                     GetTypeFromParser(ObjectType),
687219077Sdim                                     EnteringContext, SS,
688219077Sdim                                     /*ScopeLookupResult=*/0, false);
689198092Srdivacky}
690198092Srdivacky
691235633Sdimbool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
692235633Sdim                                               const DeclSpec &DS,
693235633Sdim                                               SourceLocation ColonColonLoc) {
694235633Sdim  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
695235633Sdim    return true;
696235633Sdim
697235633Sdim  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
698235633Sdim
699235633Sdim  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
700235633Sdim  if (!T->isDependentType() && !T->getAs<TagType>()) {
701235633Sdim    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class)
702235633Sdim      << T << getLangOpts().CPlusPlus;
703235633Sdim    return true;
704235633Sdim  }
705235633Sdim
706235633Sdim  TypeLocBuilder TLB;
707235633Sdim  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
708235633Sdim  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
709235633Sdim  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
710235633Sdim            ColonColonLoc);
711235633Sdim  return false;
712235633Sdim}
713235633Sdim
714200583Srdivacky/// IsInvalidUnlessNestedName - This method is used for error recovery
715200583Srdivacky/// purposes to determine whether the specified identifier is only valid as
716200583Srdivacky/// a nested name specifier, for example a namespace name.  It is
717200583Srdivacky/// conservatively correct to always return false from this method.
718200583Srdivacky///
719200583Srdivacky/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
720207619Srdivackybool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
721219077Sdim                                     IdentifierInfo &Identifier,
722219077Sdim                                     SourceLocation IdentifierLoc,
723219077Sdim                                     SourceLocation ColonLoc,
724219077Sdim                                     ParsedType ObjectType,
725200583Srdivacky                                     bool EnteringContext) {
726219077Sdim  if (SS.isInvalid())
727219077Sdim    return false;
728219077Sdim
729219077Sdim  return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
730219077Sdim                                      GetTypeFromParser(ObjectType),
731219077Sdim                                      EnteringContext, SS,
732219077Sdim                                      /*ScopeLookupResult=*/0, true);
733200583Srdivacky}
734200583Srdivacky
735219077Sdimbool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
736235633Sdim                                       CXXScopeSpec &SS,
737235633Sdim                                       SourceLocation TemplateKWLoc,
738221345Sdim                                       TemplateTy Template,
739221345Sdim                                       SourceLocation TemplateNameLoc,
740221345Sdim                                       SourceLocation LAngleLoc,
741221345Sdim                                       ASTTemplateArgsPtr TemplateArgsIn,
742221345Sdim                                       SourceLocation RAngleLoc,
743219077Sdim                                       SourceLocation CCLoc,
744221345Sdim                                       bool EnteringContext) {
745219077Sdim  if (SS.isInvalid())
746219077Sdim    return true;
747219077Sdim
748221345Sdim  // Translate the parser's template argument list in our AST format.
749221345Sdim  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
750221345Sdim  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
751221345Sdim
752221345Sdim  if (DependentTemplateName *DTN = Template.get().getAsDependentTemplateName()){
753221345Sdim    // Handle a dependent template specialization for which we cannot resolve
754221345Sdim    // the template name.
755252723Sdim    assert(DTN->getQualifier() == SS.getScopeRep());
756221345Sdim    QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
757221345Sdim                                                          DTN->getQualifier(),
758221345Sdim                                                          DTN->getIdentifier(),
759221345Sdim                                                                TemplateArgs);
760221345Sdim
761221345Sdim    // Create source-location information for this type.
762221345Sdim    TypeLocBuilder Builder;
763235633Sdim    DependentTemplateSpecializationTypeLoc SpecTL
764221345Sdim      = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
765235633Sdim    SpecTL.setElaboratedKeywordLoc(SourceLocation());
766235633Sdim    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
767235633Sdim    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
768235633Sdim    SpecTL.setTemplateNameLoc(TemplateNameLoc);
769221345Sdim    SpecTL.setLAngleLoc(LAngleLoc);
770221345Sdim    SpecTL.setRAngleLoc(RAngleLoc);
771221345Sdim    for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
772221345Sdim      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
773221345Sdim
774235633Sdim    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
775221345Sdim              CCLoc);
776221345Sdim    return false;
777221345Sdim  }
778221345Sdim
779221345Sdim
780221345Sdim  if (Template.get().getAsOverloadedTemplate() ||
781221345Sdim      isa<FunctionTemplateDecl>(Template.get().getAsTemplateDecl())) {
782221345Sdim    SourceRange R(TemplateNameLoc, RAngleLoc);
783221345Sdim    if (SS.getRange().isValid())
784221345Sdim      R.setBegin(SS.getRange().getBegin());
785221345Sdim
786221345Sdim    Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
787221345Sdim      << Template.get() << R;
788221345Sdim    NoteAllFoundTemplates(Template.get());
789221345Sdim    return true;
790221345Sdim  }
791221345Sdim
792221345Sdim  // We were able to resolve the template name to an actual template.
793221345Sdim  // Build an appropriate nested-name-specifier.
794221345Sdim  QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc,
795221345Sdim                                   TemplateArgs);
796219077Sdim  if (T.isNull())
797219077Sdim    return true;
798219077Sdim
799223017Sdim  // Alias template specializations can produce types which are not valid
800223017Sdim  // nested name specifiers.
801223017Sdim  if (!T->isDependentType() && !T->getAs<TagType>()) {
802223017Sdim    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
803223017Sdim    NoteAllFoundTemplates(Template.get());
804223017Sdim    return true;
805223017Sdim  }
806221345Sdim
807235633Sdim  // Provide source-location information for the template specialization type.
808221345Sdim  TypeLocBuilder Builder;
809235633Sdim  TemplateSpecializationTypeLoc SpecTL
810221345Sdim    = Builder.push<TemplateSpecializationTypeLoc>(T);
811235633Sdim  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
812235633Sdim  SpecTL.setTemplateNameLoc(TemplateNameLoc);
813221345Sdim  SpecTL.setLAngleLoc(LAngleLoc);
814221345Sdim  SpecTL.setRAngleLoc(RAngleLoc);
815221345Sdim  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
816221345Sdim    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
817221345Sdim
818221345Sdim
819235633Sdim  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
820221345Sdim            CCLoc);
821219077Sdim  return false;
822193326Sed}
823193326Sed
824219077Sdimnamespace {
825219077Sdim  /// \brief A structure that stores a nested-name-specifier annotation,
826219077Sdim  /// including both the nested-name-specifier
827219077Sdim  struct NestedNameSpecifierAnnotation {
828219077Sdim    NestedNameSpecifier *NNS;
829219077Sdim  };
830219077Sdim}
831219077Sdim
832219077Sdimvoid *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
833219077Sdim  if (SS.isEmpty() || SS.isInvalid())
834219077Sdim    return 0;
835219077Sdim
836219077Sdim  void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
837219077Sdim                                                        SS.location_size()),
838219077Sdim                               llvm::alignOf<NestedNameSpecifierAnnotation>());
839219077Sdim  NestedNameSpecifierAnnotation *Annotation
840219077Sdim    = new (Mem) NestedNameSpecifierAnnotation;
841219077Sdim  Annotation->NNS = SS.getScopeRep();
842219077Sdim  memcpy(Annotation + 1, SS.location_data(), SS.location_size());
843219077Sdim  return Annotation;
844219077Sdim}
845219077Sdim
846219077Sdimvoid Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
847219077Sdim                                                SourceRange AnnotationRange,
848219077Sdim                                                CXXScopeSpec &SS) {
849219077Sdim  if (!AnnotationPtr) {
850219077Sdim    SS.SetInvalid(AnnotationRange);
851219077Sdim    return;
852219077Sdim  }
853219077Sdim
854219077Sdim  NestedNameSpecifierAnnotation *Annotation
855219077Sdim    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
856219077Sdim  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
857219077Sdim}
858219077Sdim
859200583Srdivackybool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
860200583Srdivacky  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
861200583Srdivacky
862252723Sdim  NestedNameSpecifier *Qualifier = SS.getScopeRep();
863200583Srdivacky
864200583Srdivacky  // There are only two places a well-formed program may qualify a
865200583Srdivacky  // declarator: first, when defining a namespace or class member
866200583Srdivacky  // out-of-line, and second, when naming an explicitly-qualified
867200583Srdivacky  // friend function.  The latter case is governed by
868200583Srdivacky  // C++03 [basic.lookup.unqual]p10:
869200583Srdivacky  //   In a friend declaration naming a member function, a name used
870200583Srdivacky  //   in the function declarator and not part of a template-argument
871200583Srdivacky  //   in a template-id is first looked up in the scope of the member
872200583Srdivacky  //   function's class. If it is not found, or if the name is part of
873200583Srdivacky  //   a template-argument in a template-id, the look up is as
874200583Srdivacky  //   described for unqualified names in the definition of the class
875200583Srdivacky  //   granting friendship.
876200583Srdivacky  // i.e. we don't push a scope unless it's a class member.
877200583Srdivacky
878200583Srdivacky  switch (Qualifier->getKind()) {
879200583Srdivacky  case NestedNameSpecifier::Global:
880200583Srdivacky  case NestedNameSpecifier::Namespace:
881219077Sdim  case NestedNameSpecifier::NamespaceAlias:
882200583Srdivacky    // These are always namespace scopes.  We never want to enter a
883200583Srdivacky    // namespace scope from anything but a file context.
884212904Sdim    return CurContext->getRedeclContext()->isFileContext();
885200583Srdivacky
886200583Srdivacky  case NestedNameSpecifier::Identifier:
887200583Srdivacky  case NestedNameSpecifier::TypeSpec:
888200583Srdivacky  case NestedNameSpecifier::TypeSpecWithTemplate:
889200583Srdivacky    // These are never namespace scopes.
890200583Srdivacky    return true;
891200583Srdivacky  }
892200583Srdivacky
893235633Sdim  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
894200583Srdivacky}
895200583Srdivacky
896193326Sed/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
897193326Sed/// scope or nested-name-specifier) is parsed, part of a declarator-id.
898193326Sed/// After this method is called, according to [C++ 3.4.3p3], names should be
899193326Sed/// looked up in the declarator-id's scope, until the declarator is parsed and
900193326Sed/// ActOnCXXExitDeclaratorScope is called.
901193326Sed/// The 'SS' should be a non-empty valid CXXScopeSpec.
902207619Srdivackybool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
903193326Sed  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
904201361Srdivacky
905201361Srdivacky  if (SS.isInvalid()) return true;
906201361Srdivacky
907201361Srdivacky  DeclContext *DC = computeDeclContext(SS, true);
908201361Srdivacky  if (!DC) return true;
909201361Srdivacky
910201361Srdivacky  // Before we enter a declarator's context, we need to make sure that
911201361Srdivacky  // it is a complete declaration context.
912207619Srdivacky  if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
913201361Srdivacky    return true;
914201361Srdivacky
915201361Srdivacky  EnterDeclaratorContext(S, DC);
916207619Srdivacky
917207619Srdivacky  // Rebuild the nested name specifier for the new scope.
918207619Srdivacky  if (DC->isDependentContext())
919207619Srdivacky    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
920207619Srdivacky
921198092Srdivacky  return false;
922193326Sed}
923193326Sed
924193326Sed/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
925193326Sed/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
926193326Sed/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
927193326Sed/// Used to indicate that names should revert to being looked up in the
928193326Sed/// defining scope.
929193326Sedvoid Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
930193326Sed  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
931198092Srdivacky  if (SS.isInvalid())
932198092Srdivacky    return;
933201361Srdivacky  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
934201361Srdivacky         "exiting declarator scope we never really entered");
935201361Srdivacky  ExitDeclaratorContext(S);
936193326Sed}
937