SemaCXXScopeSpec.cpp 43 KB

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