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