SemaCXXScopeSpec.cpp 43 KB

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