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