• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- 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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/NestedNameSpecifier.h"
20 #include "clang/Basic/PartialDiagnostic.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/Template.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
27 
28 /// \brief Find the current instantiation that associated with the given type.
getCurrentInstantiationOf(QualType T,DeclContext * CurContext)29 static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
30                                                 DeclContext *CurContext) {
31   if (T.isNull())
32     return 0;
33 
34   const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
35   if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
36     CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
37     if (!Record->isDependentContext() ||
38         Record->isCurrentInstantiation(CurContext))
39       return Record;
40 
41     return 0;
42   } else if (isa<InjectedClassNameType>(Ty))
43     return cast<InjectedClassNameType>(Ty)->getDecl();
44   else
45     return 0;
46 }
47 
48 /// \brief Compute the DeclContext that is associated with the given type.
49 ///
50 /// \param T the type for which we are attempting to find a DeclContext.
51 ///
52 /// \returns the declaration context represented by the type T,
53 /// or NULL if the declaration context cannot be computed (e.g., because it is
54 /// dependent and not the current instantiation).
computeDeclContext(QualType T)55 DeclContext *Sema::computeDeclContext(QualType T) {
56   if (!T->isDependentType())
57     if (const TagType *Tag = T->getAs<TagType>())
58       return Tag->getDecl();
59 
60   return ::getCurrentInstantiationOf(T, CurContext);
61 }
62 
63 /// \brief Compute the DeclContext that is associated with the given
64 /// scope specifier.
65 ///
66 /// \param SS the C++ scope specifier as it appears in the source
67 ///
68 /// \param EnteringContext when true, we will be entering the context of
69 /// this scope specifier, so we can retrieve the declaration context of a
70 /// class template or class template partial specialization even if it is
71 /// not the current instantiation.
72 ///
73 /// \returns the declaration context represented by the scope specifier @p SS,
74 /// or NULL if the declaration context cannot be computed (e.g., because it is
75 /// dependent and not the current instantiation).
computeDeclContext(const CXXScopeSpec & SS,bool EnteringContext)76 DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
77                                       bool EnteringContext) {
78   if (!SS.isSet() || SS.isInvalid())
79     return 0;
80 
81   NestedNameSpecifier *NNS
82     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
83   if (NNS->isDependent()) {
84     // If this nested-name-specifier refers to the current
85     // instantiation, return its DeclContext.
86     if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
87       return Record;
88 
89     if (EnteringContext) {
90       const Type *NNSType = NNS->getAsType();
91       if (!NNSType) {
92         return 0;
93       }
94 
95       // Look through type alias templates, per C++0x [temp.dep.type]p1.
96       NNSType = Context.getCanonicalType(NNSType);
97       if (const TemplateSpecializationType *SpecType
98             = NNSType->getAs<TemplateSpecializationType>()) {
99         // We are entering the context of the nested name specifier, so try to
100         // match the nested name specifier to either a primary class template
101         // or a class template partial specialization.
102         if (ClassTemplateDecl *ClassTemplate
103               = dyn_cast_or_null<ClassTemplateDecl>(
104                             SpecType->getTemplateName().getAsTemplateDecl())) {
105           QualType ContextType
106             = Context.getCanonicalType(QualType(SpecType, 0));
107 
108           // If the type of the nested name specifier is the same as the
109           // injected class name of the named class template, we're entering
110           // into that class template definition.
111           QualType Injected
112             = ClassTemplate->getInjectedClassNameSpecialization();
113           if (Context.hasSameType(Injected, ContextType))
114             return ClassTemplate->getTemplatedDecl();
115 
116           // If the type of the nested name specifier is the same as the
117           // type of one of the class template's class template partial
118           // specializations, we're entering into the definition of that
119           // class template partial specialization.
120           if (ClassTemplatePartialSpecializationDecl *PartialSpec
121                 = ClassTemplate->findPartialSpecialization(ContextType))
122             return PartialSpec;
123         }
124       } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
125         // The nested name specifier refers to a member of a class template.
126         return RecordT->getDecl();
127       }
128     }
129 
130     return 0;
131   }
132 
133   switch (NNS->getKind()) {
134   case NestedNameSpecifier::Identifier:
135     llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
136 
137   case NestedNameSpecifier::Namespace:
138     return NNS->getAsNamespace();
139 
140   case NestedNameSpecifier::NamespaceAlias:
141     return NNS->getAsNamespaceAlias()->getNamespace();
142 
143   case NestedNameSpecifier::TypeSpec:
144   case NestedNameSpecifier::TypeSpecWithTemplate: {
145     const TagType *Tag = NNS->getAsType()->getAs<TagType>();
146     assert(Tag && "Non-tag type in nested-name-specifier");
147     return Tag->getDecl();
148   }
149 
150   case NestedNameSpecifier::Global:
151     return Context.getTranslationUnitDecl();
152   }
153 
154   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
155 }
156 
isDependentScopeSpecifier(const CXXScopeSpec & SS)157 bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
158   if (!SS.isSet() || SS.isInvalid())
159     return false;
160 
161   NestedNameSpecifier *NNS
162     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
163   return NNS->isDependent();
164 }
165 
166 // \brief Determine whether this C++ scope specifier refers to an
167 // unknown specialization, i.e., a dependent type that is not the
168 // current instantiation.
isUnknownSpecialization(const CXXScopeSpec & SS)169 bool Sema::isUnknownSpecialization(const CXXScopeSpec &SS) {
170   if (!isDependentScopeSpecifier(SS))
171     return false;
172 
173   NestedNameSpecifier *NNS
174     = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
175   return getCurrentInstantiationOf(NNS) == 0;
176 }
177 
178 /// \brief If the given nested name specifier refers to the current
179 /// instantiation, return the declaration that corresponds to that
180 /// current instantiation (C++0x [temp.dep.type]p1).
181 ///
182 /// \param NNS a dependent nested name specifier.
getCurrentInstantiationOf(NestedNameSpecifier * NNS)183 CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
184   assert(getLangOpts().CPlusPlus && "Only callable in C++");
185   assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
186 
187   if (!NNS->getAsType())
188     return 0;
189 
190   QualType T = QualType(NNS->getAsType(), 0);
191   return ::getCurrentInstantiationOf(T, CurContext);
192 }
193 
194 /// \brief Require that the context specified by SS be complete.
195 ///
196 /// If SS refers to a type, this routine checks whether the type is
197 /// complete enough (or can be made complete enough) for name lookup
198 /// into the DeclContext. A type that is not yet completed can be
199 /// considered "complete enough" if it is a class/struct/union/enum
200 /// that is currently being defined. Or, if we have a type that names
201 /// a class template specialization that is not a complete type, we
202 /// will attempt to instantiate that class template.
RequireCompleteDeclContext(CXXScopeSpec & SS,DeclContext * DC)203 bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
204                                       DeclContext *DC) {
205   assert(DC != 0 && "given null context");
206 
207   TagDecl *tag = dyn_cast<TagDecl>(DC);
208 
209   // If this is a dependent type, then we consider it complete.
210   if (!tag || tag->isDependentContext())
211     return false;
212 
213   // If we're currently defining this type, then lookup into the
214   // type is okay: don't complain that it isn't complete yet.
215   QualType type = Context.getTypeDeclType(tag);
216   const TagType *tagType = type->getAs<TagType>();
217   if (tagType && tagType->isBeingDefined())
218     return false;
219 
220   SourceLocation loc = SS.getLastQualifierNameLoc();
221   if (loc.isInvalid()) loc = SS.getRange().getBegin();
222 
223   // The type must be complete.
224   if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
225                           SS.getRange())) {
226     SS.SetInvalid(SS.getRange());
227     return true;
228   }
229 
230   // Fixed enum types are complete, but they aren't valid as scopes
231   // until we see a definition, so awkwardly pull out this special
232   // case.
233   const EnumType *enumType = dyn_cast_or_null<EnumType>(tagType);
234   if (!enumType || enumType->getDecl()->isCompleteDefinition())
235     return false;
236 
237   // Try to instantiate the definition, if this is a specialization of an
238   // enumeration temploid.
239   EnumDecl *ED = enumType->getDecl();
240   if (EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
241     MemberSpecializationInfo *MSI = ED->getMemberSpecializationInfo();
242     if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
243       if (InstantiateEnum(loc, ED, Pattern, getTemplateInstantiationArgs(ED),
244                           TSK_ImplicitInstantiation)) {
245         SS.SetInvalid(SS.getRange());
246         return true;
247       }
248       return false;
249     }
250   }
251 
252   Diag(loc, diag::err_incomplete_nested_name_spec)
253     << type << SS.getRange();
254   SS.SetInvalid(SS.getRange());
255   return true;
256 }
257 
ActOnCXXGlobalScopeSpecifier(Scope * S,SourceLocation CCLoc,CXXScopeSpec & SS)258 bool Sema::ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc,
259                                         CXXScopeSpec &SS) {
260   SS.MakeGlobal(Context, CCLoc);
261   return false;
262 }
263 
264 /// \brief Determines whether the given declaration is an valid acceptable
265 /// result for name lookup of a nested-name-specifier.
isAcceptableNestedNameSpecifier(const NamedDecl * SD)266 bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD) {
267   if (!SD)
268     return false;
269 
270   // Namespace and namespace aliases are fine.
271   if (isa<NamespaceDecl>(SD) || isa<NamespaceAliasDecl>(SD))
272     return true;
273 
274   if (!isa<TypeDecl>(SD))
275     return false;
276 
277   // Determine whether we have a class (or, in C++11, an enum) or
278   // a typedef thereof. If so, build the nested-name-specifier.
279   QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
280   if (T->isDependentType())
281     return true;
282   else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
283     if (TD->getUnderlyingType()->isRecordType() ||
284         (Context.getLangOpts().CPlusPlus11 &&
285          TD->getUnderlyingType()->isEnumeralType()))
286       return true;
287   } else if (isa<RecordDecl>(SD) ||
288              (Context.getLangOpts().CPlusPlus11 && isa<EnumDecl>(SD)))
289     return true;
290 
291   return false;
292 }
293 
294 /// \brief If the given nested-name-specifier begins with a bare identifier
295 /// (e.g., Base::), perform name lookup for that identifier as a
296 /// nested-name-specifier within the given scope, and return the result of that
297 /// name lookup.
FindFirstQualifierInScope(Scope * S,NestedNameSpecifier * NNS)298 NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
299   if (!S || !NNS)
300     return 0;
301 
302   while (NNS->getPrefix())
303     NNS = NNS->getPrefix();
304 
305   if (NNS->getKind() != NestedNameSpecifier::Identifier)
306     return 0;
307 
308   LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
309                      LookupNestedNameSpecifierName);
310   LookupName(Found, S);
311   assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
312 
313   if (!Found.isSingleResult())
314     return 0;
315 
316   NamedDecl *Result = Found.getFoundDecl();
317   if (isAcceptableNestedNameSpecifier(Result))
318     return Result;
319 
320   return 0;
321 }
322 
isNonTypeNestedNameSpecifier(Scope * S,CXXScopeSpec & SS,SourceLocation IdLoc,IdentifierInfo & II,ParsedType ObjectTypePtr)323 bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
324                                         SourceLocation IdLoc,
325                                         IdentifierInfo &II,
326                                         ParsedType ObjectTypePtr) {
327   QualType ObjectType = GetTypeFromParser(ObjectTypePtr);
328   LookupResult Found(*this, &II, IdLoc, LookupNestedNameSpecifierName);
329 
330   // Determine where to perform name lookup
331   DeclContext *LookupCtx = 0;
332   bool isDependent = false;
333   if (!ObjectType.isNull()) {
334     // This nested-name-specifier occurs in a member access expression, e.g.,
335     // x->B::f, and we are looking into the type of the object.
336     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
337     LookupCtx = computeDeclContext(ObjectType);
338     isDependent = ObjectType->isDependentType();
339   } else if (SS.isSet()) {
340     // This nested-name-specifier occurs after another nested-name-specifier,
341     // so long into the context associated with the prior nested-name-specifier.
342     LookupCtx = computeDeclContext(SS, false);
343     isDependent = isDependentScopeSpecifier(SS);
344     Found.setContextRange(SS.getRange());
345   }
346 
347   if (LookupCtx) {
348     // Perform "qualified" name lookup into the declaration context we
349     // computed, which is either the type of the base of a member access
350     // expression or the declaration context associated with a prior
351     // nested-name-specifier.
352 
353     // The declaration context must be complete.
354     if (!LookupCtx->isDependentContext() &&
355         RequireCompleteDeclContext(SS, LookupCtx))
356       return false;
357 
358     LookupQualifiedName(Found, LookupCtx);
359   } else if (isDependent) {
360     return false;
361   } else {
362     LookupName(Found, S);
363   }
364   Found.suppressDiagnostics();
365 
366   if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
367     return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
368 
369   return false;
370 }
371 
372 namespace {
373 
374 // Callback to only accept typo corrections that can be a valid C++ member
375 // intializer: either a non-static field member or a base class.
376 class NestedNameSpecifierValidatorCCC : public CorrectionCandidateCallback {
377  public:
NestedNameSpecifierValidatorCCC(Sema & SRef)378   explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
379       : SRef(SRef) {}
380 
ValidateCandidate(const TypoCorrection & candidate)381   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
382     return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
383   }
384 
385  private:
386   Sema &SRef;
387 };
388 
389 }
390 
391 /// \brief Build a new nested-name-specifier for "identifier::", as described
392 /// by ActOnCXXNestedNameSpecifier.
393 ///
394 /// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
395 /// that it contains an extra parameter \p ScopeLookupResult, which provides
396 /// the result of name lookup within the scope of the nested-name-specifier
397 /// that was computed at template definition time.
398 ///
399 /// If ErrorRecoveryLookup is true, then this call is used to improve error
400 /// recovery.  This means that it should not emit diagnostics, it should
401 /// just return true on failure.  It also means it should only return a valid
402 /// scope if it *knows* that the result is correct.  It should not return in a
403 /// dependent context, for example. Nor will it extend \p SS with the scope
404 /// specifier.
BuildCXXNestedNameSpecifier(Scope * S,IdentifierInfo & Identifier,SourceLocation IdentifierLoc,SourceLocation CCLoc,QualType ObjectType,bool EnteringContext,CXXScopeSpec & SS,NamedDecl * ScopeLookupResult,bool ErrorRecoveryLookup)405 bool Sema::BuildCXXNestedNameSpecifier(Scope *S,
406                                        IdentifierInfo &Identifier,
407                                        SourceLocation IdentifierLoc,
408                                        SourceLocation CCLoc,
409                                        QualType ObjectType,
410                                        bool EnteringContext,
411                                        CXXScopeSpec &SS,
412                                        NamedDecl *ScopeLookupResult,
413                                        bool ErrorRecoveryLookup) {
414   LookupResult Found(*this, &Identifier, IdentifierLoc,
415                      LookupNestedNameSpecifierName);
416 
417   // Determine where to perform name lookup
418   DeclContext *LookupCtx = 0;
419   bool isDependent = false;
420   if (!ObjectType.isNull()) {
421     // This nested-name-specifier occurs in a member access expression, e.g.,
422     // x->B::f, and we are looking into the type of the object.
423     assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
424     LookupCtx = computeDeclContext(ObjectType);
425     isDependent = ObjectType->isDependentType();
426   } else if (SS.isSet()) {
427     // This nested-name-specifier occurs after another nested-name-specifier,
428     // so look into the context associated with the prior nested-name-specifier.
429     LookupCtx = computeDeclContext(SS, EnteringContext);
430     isDependent = isDependentScopeSpecifier(SS);
431     Found.setContextRange(SS.getRange());
432   }
433 
434 
435   bool ObjectTypeSearchedInScope = false;
436   if (LookupCtx) {
437     // Perform "qualified" name lookup into the declaration context we
438     // computed, which is either the type of the base of a member access
439     // expression or the declaration context associated with a prior
440     // nested-name-specifier.
441 
442     // The declaration context must be complete.
443     if (!LookupCtx->isDependentContext() &&
444         RequireCompleteDeclContext(SS, LookupCtx))
445       return true;
446 
447     LookupQualifiedName(Found, LookupCtx);
448 
449     if (!ObjectType.isNull() && Found.empty()) {
450       // C++ [basic.lookup.classref]p4:
451       //   If the id-expression in a class member access is a qualified-id of
452       //   the form
453       //
454       //        class-name-or-namespace-name::...
455       //
456       //   the class-name-or-namespace-name following the . or -> operator is
457       //   looked up both in the context of the entire postfix-expression and in
458       //   the scope of the class of the object expression. If the name is found
459       //   only in the scope of the class of the object expression, the name
460       //   shall refer to a class-name. If the name is found only in the
461       //   context of the entire postfix-expression, the name shall refer to a
462       //   class-name or namespace-name. [...]
463       //
464       // Qualified name lookup into a class will not find a namespace-name,
465       // so we do not need to diagnose that case specifically. However,
466       // this qualified name lookup may find nothing. In that case, perform
467       // unqualified name lookup in the given scope (if available) or
468       // reconstruct the result from when name lookup was performed at template
469       // definition time.
470       if (S)
471         LookupName(Found, S);
472       else if (ScopeLookupResult)
473         Found.addDecl(ScopeLookupResult);
474 
475       ObjectTypeSearchedInScope = true;
476     }
477   } else if (!isDependent) {
478     // Perform unqualified name lookup in the current scope.
479     LookupName(Found, S);
480   }
481 
482   // If we performed lookup into a dependent context and did not find anything,
483   // that's fine: just build a dependent nested-name-specifier.
484   if (Found.empty() && isDependent &&
485       !(LookupCtx && LookupCtx->isRecord() &&
486         (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
487          !cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()))) {
488     // Don't speculate if we're just trying to improve error recovery.
489     if (ErrorRecoveryLookup)
490       return true;
491 
492     // We were not able to compute the declaration context for a dependent
493     // base object type or prior nested-name-specifier, so this
494     // nested-name-specifier refers to an unknown specialization. Just build
495     // a dependent nested-name-specifier.
496     SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
497     return false;
498   }
499 
500   // FIXME: Deal with ambiguities cleanly.
501 
502   if (Found.empty() && !ErrorRecoveryLookup) {
503     // We haven't found anything, and we're not recovering from a
504     // different kind of error, so look for typos.
505     DeclarationName Name = Found.getLookupName();
506     NestedNameSpecifierValidatorCCC Validator(*this);
507     TypoCorrection Corrected;
508     Found.clear();
509     if ((Corrected = CorrectTypo(Found.getLookupNameInfo(),
510                                  Found.getLookupKind(), S, &SS, Validator,
511                                  LookupCtx, EnteringContext))) {
512       std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513       std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
514       if (LookupCtx)
515         Diag(Found.getNameLoc(), diag::err_no_member_suggest)
516           << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
517           << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
518                                           CorrectedStr);
519       else
520         Diag(Found.getNameLoc(), diag::err_undeclared_var_use_suggest)
521           << Name << CorrectedQuotedStr
522           << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
523 
524       if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
525         Diag(ND->getLocation(), diag::note_previous_decl) << CorrectedQuotedStr;
526         Found.addDecl(ND);
527       }
528       Found.setLookupName(Corrected.getCorrection());
529     } else {
530       Found.setLookupName(&Identifier);
531     }
532   }
533 
534   NamedDecl *SD = Found.getAsSingle<NamedDecl>();
535   if (isAcceptableNestedNameSpecifier(SD)) {
536     if (!ObjectType.isNull() && !ObjectTypeSearchedInScope &&
537         !getLangOpts().CPlusPlus11) {
538       // C++03 [basic.lookup.classref]p4:
539       //   [...] If the name is found in both contexts, the
540       //   class-name-or-namespace-name shall refer to the same entity.
541       //
542       // We already found the name in the scope of the object. Now, look
543       // into the current scope (the scope of the postfix-expression) to
544       // see if we can find the same name there. As above, if there is no
545       // scope, reconstruct the result from the template instantiation itself.
546       //
547       // Note that C++11 does *not* perform this redundant lookup.
548       NamedDecl *OuterDecl;
549       if (S) {
550         LookupResult FoundOuter(*this, &Identifier, IdentifierLoc,
551                                 LookupNestedNameSpecifierName);
552         LookupName(FoundOuter, S);
553         OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
554       } else
555         OuterDecl = ScopeLookupResult;
556 
557       if (isAcceptableNestedNameSpecifier(OuterDecl) &&
558           OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl() &&
559           (!isa<TypeDecl>(OuterDecl) || !isa<TypeDecl>(SD) ||
560            !Context.hasSameType(
561                             Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
562                                Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
563          if (ErrorRecoveryLookup)
564            return true;
565 
566          Diag(IdentifierLoc,
567               diag::err_nested_name_member_ref_lookup_ambiguous)
568            << &Identifier;
569          Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
570            << ObjectType;
571          Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
572 
573          // Fall through so that we'll pick the name we found in the object
574          // type, since that's probably what the user wanted anyway.
575        }
576     }
577 
578     // If we're just performing this lookup for error-recovery purposes,
579     // don't extend the nested-name-specifier. Just return now.
580     if (ErrorRecoveryLookup)
581       return false;
582 
583     if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
584       SS.Extend(Context, Namespace, IdentifierLoc, CCLoc);
585       return false;
586     }
587 
588     if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
589       SS.Extend(Context, Alias, IdentifierLoc, CCLoc);
590       return false;
591     }
592 
593     QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
594     TypeLocBuilder TLB;
595     if (isa<InjectedClassNameType>(T)) {
596       InjectedClassNameTypeLoc InjectedTL
597         = TLB.push<InjectedClassNameTypeLoc>(T);
598       InjectedTL.setNameLoc(IdentifierLoc);
599     } else if (isa<RecordType>(T)) {
600       RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
601       RecordTL.setNameLoc(IdentifierLoc);
602     } else if (isa<TypedefType>(T)) {
603       TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
604       TypedefTL.setNameLoc(IdentifierLoc);
605     } else if (isa<EnumType>(T)) {
606       EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
607       EnumTL.setNameLoc(IdentifierLoc);
608     } else if (isa<TemplateTypeParmType>(T)) {
609       TemplateTypeParmTypeLoc TemplateTypeTL
610         = TLB.push<TemplateTypeParmTypeLoc>(T);
611       TemplateTypeTL.setNameLoc(IdentifierLoc);
612     } else if (isa<UnresolvedUsingType>(T)) {
613       UnresolvedUsingTypeLoc UnresolvedTL
614         = TLB.push<UnresolvedUsingTypeLoc>(T);
615       UnresolvedTL.setNameLoc(IdentifierLoc);
616     } else if (isa<SubstTemplateTypeParmType>(T)) {
617       SubstTemplateTypeParmTypeLoc TL
618         = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
619       TL.setNameLoc(IdentifierLoc);
620     } else if (isa<SubstTemplateTypeParmPackType>(T)) {
621       SubstTemplateTypeParmPackTypeLoc TL
622         = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
623       TL.setNameLoc(IdentifierLoc);
624     } else {
625       llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
626     }
627 
628     if (T->isEnumeralType())
629       Diag(IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
630 
631     SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
632               CCLoc);
633     return false;
634   }
635 
636   // Otherwise, we have an error case.  If we don't want diagnostics, just
637   // return an error now.
638   if (ErrorRecoveryLookup)
639     return true;
640 
641   // If we didn't find anything during our lookup, try again with
642   // ordinary name lookup, which can help us produce better error
643   // messages.
644   if (Found.empty()) {
645     Found.clear(LookupOrdinaryName);
646     LookupName(Found, S);
647   }
648 
649   // In Microsoft mode, if we are within a templated function and we can't
650   // resolve Identifier, then extend the SS with Identifier. This will have
651   // the effect of resolving Identifier during template instantiation.
652   // The goal is to be able to resolve a function call whose
653   // nested-name-specifier is located inside a dependent base class.
654   // Example:
655   //
656   // class C {
657   // public:
658   //    static void foo2() {  }
659   // };
660   // template <class T> class A { public: typedef C D; };
661   //
662   // template <class T> class B : public A<T> {
663   // public:
664   //   void foo() { D::foo2(); }
665   // };
666   if (getLangOpts().MicrosoftExt) {
667     DeclContext *DC = LookupCtx ? LookupCtx : CurContext;
668     if (DC->isDependentContext() && DC->isFunctionOrMethod()) {
669       SS.Extend(Context, &Identifier, IdentifierLoc, CCLoc);
670       return false;
671     }
672   }
673 
674   unsigned DiagID;
675   if (!Found.empty())
676     DiagID = diag::err_expected_class_or_namespace;
677   else if (SS.isSet()) {
678     Diag(IdentifierLoc, diag::err_no_member)
679       << &Identifier << LookupCtx << SS.getRange();
680     return true;
681   } else
682     DiagID = diag::err_undeclared_var_use;
683 
684   if (SS.isSet())
685     Diag(IdentifierLoc, DiagID) << &Identifier << SS.getRange();
686   else
687     Diag(IdentifierLoc, DiagID) << &Identifier;
688 
689   return true;
690 }
691 
ActOnCXXNestedNameSpecifier(Scope * S,IdentifierInfo & Identifier,SourceLocation IdentifierLoc,SourceLocation CCLoc,ParsedType ObjectType,bool EnteringContext,CXXScopeSpec & SS)692 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
693                                        IdentifierInfo &Identifier,
694                                        SourceLocation IdentifierLoc,
695                                        SourceLocation CCLoc,
696                                        ParsedType ObjectType,
697                                        bool EnteringContext,
698                                        CXXScopeSpec &SS) {
699   if (SS.isInvalid())
700     return true;
701 
702   return BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, CCLoc,
703                                      GetTypeFromParser(ObjectType),
704                                      EnteringContext, SS,
705                                      /*ScopeLookupResult=*/0, false);
706 }
707 
ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec & SS,const DeclSpec & DS,SourceLocation ColonColonLoc)708 bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
709                                                const DeclSpec &DS,
710                                                SourceLocation ColonColonLoc) {
711   if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
712     return true;
713 
714   assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
715 
716   QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
717   if (!T->isDependentType() && !T->getAs<TagType>()) {
718     Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class)
719       << T << getLangOpts().CPlusPlus;
720     return true;
721   }
722 
723   TypeLocBuilder TLB;
724   DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
725   DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
726   SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
727             ColonColonLoc);
728   return false;
729 }
730 
731 /// IsInvalidUnlessNestedName - This method is used for error recovery
732 /// purposes to determine whether the specified identifier is only valid as
733 /// a nested name specifier, for example a namespace name.  It is
734 /// conservatively correct to always return false from this method.
735 ///
736 /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
IsInvalidUnlessNestedName(Scope * S,CXXScopeSpec & SS,IdentifierInfo & Identifier,SourceLocation IdentifierLoc,SourceLocation ColonLoc,ParsedType ObjectType,bool EnteringContext)737 bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
738                                      IdentifierInfo &Identifier,
739                                      SourceLocation IdentifierLoc,
740                                      SourceLocation ColonLoc,
741                                      ParsedType ObjectType,
742                                      bool EnteringContext) {
743   if (SS.isInvalid())
744     return false;
745 
746   return !BuildCXXNestedNameSpecifier(S, Identifier, IdentifierLoc, ColonLoc,
747                                       GetTypeFromParser(ObjectType),
748                                       EnteringContext, SS,
749                                       /*ScopeLookupResult=*/0, true);
750 }
751 
ActOnCXXNestedNameSpecifier(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy Template,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,SourceLocation CCLoc,bool EnteringContext)752 bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
753                                        CXXScopeSpec &SS,
754                                        SourceLocation TemplateKWLoc,
755                                        TemplateTy Template,
756                                        SourceLocation TemplateNameLoc,
757                                        SourceLocation LAngleLoc,
758                                        ASTTemplateArgsPtr TemplateArgsIn,
759                                        SourceLocation RAngleLoc,
760                                        SourceLocation CCLoc,
761                                        bool EnteringContext) {
762   if (SS.isInvalid())
763     return true;
764 
765   // Translate the parser's template argument list in our AST format.
766   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
767   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
768 
769   if (DependentTemplateName *DTN = Template.get().getAsDependentTemplateName()){
770     // Handle a dependent template specialization for which we cannot resolve
771     // the template name.
772     assert(DTN->getQualifier()
773              == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
774     QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
775                                                           DTN->getQualifier(),
776                                                           DTN->getIdentifier(),
777                                                                 TemplateArgs);
778 
779     // Create source-location information for this type.
780     TypeLocBuilder Builder;
781     DependentTemplateSpecializationTypeLoc SpecTL
782       = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
783     SpecTL.setElaboratedKeywordLoc(SourceLocation());
784     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
785     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
786     SpecTL.setTemplateNameLoc(TemplateNameLoc);
787     SpecTL.setLAngleLoc(LAngleLoc);
788     SpecTL.setRAngleLoc(RAngleLoc);
789     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
790       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
791 
792     SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
793               CCLoc);
794     return false;
795   }
796 
797 
798   if (Template.get().getAsOverloadedTemplate() ||
799       isa<FunctionTemplateDecl>(Template.get().getAsTemplateDecl())) {
800     SourceRange R(TemplateNameLoc, RAngleLoc);
801     if (SS.getRange().isValid())
802       R.setBegin(SS.getRange().getBegin());
803 
804     Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
805       << Template.get() << R;
806     NoteAllFoundTemplates(Template.get());
807     return true;
808   }
809 
810   // We were able to resolve the template name to an actual template.
811   // Build an appropriate nested-name-specifier.
812   QualType T = CheckTemplateIdType(Template.get(), TemplateNameLoc,
813                                    TemplateArgs);
814   if (T.isNull())
815     return true;
816 
817   // Alias template specializations can produce types which are not valid
818   // nested name specifiers.
819   if (!T->isDependentType() && !T->getAs<TagType>()) {
820     Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
821     NoteAllFoundTemplates(Template.get());
822     return true;
823   }
824 
825   // Provide source-location information for the template specialization type.
826   TypeLocBuilder Builder;
827   TemplateSpecializationTypeLoc SpecTL
828     = Builder.push<TemplateSpecializationTypeLoc>(T);
829   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
830   SpecTL.setTemplateNameLoc(TemplateNameLoc);
831   SpecTL.setLAngleLoc(LAngleLoc);
832   SpecTL.setRAngleLoc(RAngleLoc);
833   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
834     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
835 
836 
837   SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
838             CCLoc);
839   return false;
840 }
841 
842 namespace {
843   /// \brief A structure that stores a nested-name-specifier annotation,
844   /// including both the nested-name-specifier
845   struct NestedNameSpecifierAnnotation {
846     NestedNameSpecifier *NNS;
847   };
848 }
849 
SaveNestedNameSpecifierAnnotation(CXXScopeSpec & SS)850 void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
851   if (SS.isEmpty() || SS.isInvalid())
852     return 0;
853 
854   void *Mem = Context.Allocate((sizeof(NestedNameSpecifierAnnotation) +
855                                                         SS.location_size()),
856                                llvm::alignOf<NestedNameSpecifierAnnotation>());
857   NestedNameSpecifierAnnotation *Annotation
858     = new (Mem) NestedNameSpecifierAnnotation;
859   Annotation->NNS = SS.getScopeRep();
860   memcpy(Annotation + 1, SS.location_data(), SS.location_size());
861   return Annotation;
862 }
863 
RestoreNestedNameSpecifierAnnotation(void * AnnotationPtr,SourceRange AnnotationRange,CXXScopeSpec & SS)864 void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
865                                                 SourceRange AnnotationRange,
866                                                 CXXScopeSpec &SS) {
867   if (!AnnotationPtr) {
868     SS.SetInvalid(AnnotationRange);
869     return;
870   }
871 
872   NestedNameSpecifierAnnotation *Annotation
873     = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
874   SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
875 }
876 
ShouldEnterDeclaratorScope(Scope * S,const CXXScopeSpec & SS)877 bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
878   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
879 
880   NestedNameSpecifier *Qualifier =
881     static_cast<NestedNameSpecifier*>(SS.getScopeRep());
882 
883   // There are only two places a well-formed program may qualify a
884   // declarator: first, when defining a namespace or class member
885   // out-of-line, and second, when naming an explicitly-qualified
886   // friend function.  The latter case is governed by
887   // C++03 [basic.lookup.unqual]p10:
888   //   In a friend declaration naming a member function, a name used
889   //   in the function declarator and not part of a template-argument
890   //   in a template-id is first looked up in the scope of the member
891   //   function's class. If it is not found, or if the name is part of
892   //   a template-argument in a template-id, the look up is as
893   //   described for unqualified names in the definition of the class
894   //   granting friendship.
895   // i.e. we don't push a scope unless it's a class member.
896 
897   switch (Qualifier->getKind()) {
898   case NestedNameSpecifier::Global:
899   case NestedNameSpecifier::Namespace:
900   case NestedNameSpecifier::NamespaceAlias:
901     // These are always namespace scopes.  We never want to enter a
902     // namespace scope from anything but a file context.
903     return CurContext->getRedeclContext()->isFileContext();
904 
905   case NestedNameSpecifier::Identifier:
906   case NestedNameSpecifier::TypeSpec:
907   case NestedNameSpecifier::TypeSpecWithTemplate:
908     // These are never namespace scopes.
909     return true;
910   }
911 
912   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
913 }
914 
915 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
916 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
917 /// After this method is called, according to [C++ 3.4.3p3], names should be
918 /// looked up in the declarator-id's scope, until the declarator is parsed and
919 /// ActOnCXXExitDeclaratorScope is called.
920 /// The 'SS' should be a non-empty valid CXXScopeSpec.
ActOnCXXEnterDeclaratorScope(Scope * S,CXXScopeSpec & SS)921 bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
922   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
923 
924   if (SS.isInvalid()) return true;
925 
926   DeclContext *DC = computeDeclContext(SS, true);
927   if (!DC) return true;
928 
929   // Before we enter a declarator's context, we need to make sure that
930   // it is a complete declaration context.
931   if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
932     return true;
933 
934   EnterDeclaratorContext(S, DC);
935 
936   // Rebuild the nested name specifier for the new scope.
937   if (DC->isDependentContext())
938     RebuildNestedNameSpecifierInCurrentInstantiation(SS);
939 
940   return false;
941 }
942 
943 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
944 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
945 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
946 /// Used to indicate that names should revert to being looked up in the
947 /// defining scope.
ActOnCXXExitDeclaratorScope(Scope * S,const CXXScopeSpec & SS)948 void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
949   assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
950   if (SS.isInvalid())
951     return;
952   assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
953          "exiting declarator scope we never really entered");
954   ExitDeclaratorContext(S);
955 }
956