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