SemaCXXScopeSpec.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  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 (!hasReachableDefinition(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 (!hasReachableDefinition(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 if (Found.getAsSingle<TemplateDecl>()) {
  737. ParsedType SuggestedType;
  738. DiagnoseUnknownTypeName(IdInfo.Identifier, IdInfo.IdentifierLoc, S, &SS,
  739. SuggestedType);
  740. } else {
  741. Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
  742. << IdInfo.Identifier << getLangOpts().CPlusPlus;
  743. if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
  744. Diag(ND->getLocation(), diag::note_entity_declared_at)
  745. << IdInfo.Identifier;
  746. }
  747. } else if (SS.isSet())
  748. Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
  749. << LookupCtx << SS.getRange();
  750. else
  751. Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
  752. << IdInfo.Identifier;
  753. return true;
  754. }
  755. bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
  756. bool EnteringContext, CXXScopeSpec &SS,
  757. bool *IsCorrectedToColon,
  758. bool OnlyNamespace) {
  759. if (SS.isInvalid())
  760. return true;
  761. return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
  762. /*ScopeLookupResult=*/nullptr, false,
  763. IsCorrectedToColon, OnlyNamespace);
  764. }
  765. bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
  766. const DeclSpec &DS,
  767. SourceLocation ColonColonLoc) {
  768. if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
  769. return true;
  770. assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
  771. QualType T = BuildDecltypeType(DS.getRepAsExpr());
  772. if (T.isNull())
  773. return true;
  774. if (!T->isDependentType() && !T->getAs<TagType>()) {
  775. Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
  776. << T << getLangOpts().CPlusPlus;
  777. return true;
  778. }
  779. TypeLocBuilder TLB;
  780. DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
  781. DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
  782. DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
  783. SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
  784. ColonColonLoc);
  785. return false;
  786. }
  787. /// IsInvalidUnlessNestedName - This method is used for error recovery
  788. /// purposes to determine whether the specified identifier is only valid as
  789. /// a nested name specifier, for example a namespace name. It is
  790. /// conservatively correct to always return false from this method.
  791. ///
  792. /// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
  793. bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
  794. NestedNameSpecInfo &IdInfo,
  795. bool EnteringContext) {
  796. if (SS.isInvalid())
  797. return false;
  798. return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
  799. /*ScopeLookupResult=*/nullptr, true);
  800. }
  801. bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
  802. CXXScopeSpec &SS,
  803. SourceLocation TemplateKWLoc,
  804. TemplateTy OpaqueTemplate,
  805. SourceLocation TemplateNameLoc,
  806. SourceLocation LAngleLoc,
  807. ASTTemplateArgsPtr TemplateArgsIn,
  808. SourceLocation RAngleLoc,
  809. SourceLocation CCLoc,
  810. bool EnteringContext) {
  811. if (SS.isInvalid())
  812. return true;
  813. TemplateName Template = OpaqueTemplate.get();
  814. // Translate the parser's template argument list in our AST format.
  815. TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
  816. translateTemplateArguments(TemplateArgsIn, TemplateArgs);
  817. DependentTemplateName *DTN = Template.getAsDependentTemplateName();
  818. if (DTN && DTN->isIdentifier()) {
  819. // Handle a dependent template specialization for which we cannot resolve
  820. // the template name.
  821. assert(DTN->getQualifier() == SS.getScopeRep());
  822. QualType T = Context.getDependentTemplateSpecializationType(
  823. ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
  824. TemplateArgs.arguments());
  825. // Create source-location information for this type.
  826. TypeLocBuilder Builder;
  827. DependentTemplateSpecializationTypeLoc SpecTL
  828. = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
  829. SpecTL.setElaboratedKeywordLoc(SourceLocation());
  830. SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
  831. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  832. SpecTL.setTemplateNameLoc(TemplateNameLoc);
  833. SpecTL.setLAngleLoc(LAngleLoc);
  834. SpecTL.setRAngleLoc(RAngleLoc);
  835. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  836. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  837. SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
  838. CCLoc);
  839. return false;
  840. }
  841. // If we assumed an undeclared identifier was a template name, try to
  842. // typo-correct it now.
  843. if (Template.getAsAssumedTemplateName() &&
  844. resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc))
  845. return true;
  846. TemplateDecl *TD = Template.getAsTemplateDecl();
  847. if (Template.getAsOverloadedTemplate() || DTN ||
  848. isa<FunctionTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)) {
  849. SourceRange R(TemplateNameLoc, RAngleLoc);
  850. if (SS.getRange().isValid())
  851. R.setBegin(SS.getRange().getBegin());
  852. Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
  853. << (TD && isa<VarTemplateDecl>(TD)) << Template << R;
  854. NoteAllFoundTemplates(Template);
  855. return true;
  856. }
  857. // We were able to resolve the template name to an actual template.
  858. // Build an appropriate nested-name-specifier.
  859. QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
  860. if (T.isNull())
  861. return true;
  862. // Alias template specializations can produce types which are not valid
  863. // nested name specifiers.
  864. if (!T->isDependentType() && !T->getAs<TagType>()) {
  865. Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
  866. NoteAllFoundTemplates(Template);
  867. return true;
  868. }
  869. // Provide source-location information for the template specialization type.
  870. TypeLocBuilder Builder;
  871. TemplateSpecializationTypeLoc SpecTL
  872. = Builder.push<TemplateSpecializationTypeLoc>(T);
  873. SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
  874. SpecTL.setTemplateNameLoc(TemplateNameLoc);
  875. SpecTL.setLAngleLoc(LAngleLoc);
  876. SpecTL.setRAngleLoc(RAngleLoc);
  877. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  878. SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
  879. SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
  880. CCLoc);
  881. return false;
  882. }
  883. namespace {
  884. /// A structure that stores a nested-name-specifier annotation,
  885. /// including both the nested-name-specifier
  886. struct NestedNameSpecifierAnnotation {
  887. NestedNameSpecifier *NNS;
  888. };
  889. }
  890. void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
  891. if (SS.isEmpty() || SS.isInvalid())
  892. return nullptr;
  893. void *Mem = Context.Allocate(
  894. (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
  895. alignof(NestedNameSpecifierAnnotation));
  896. NestedNameSpecifierAnnotation *Annotation
  897. = new (Mem) NestedNameSpecifierAnnotation;
  898. Annotation->NNS = SS.getScopeRep();
  899. memcpy(Annotation + 1, SS.location_data(), SS.location_size());
  900. return Annotation;
  901. }
  902. void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
  903. SourceRange AnnotationRange,
  904. CXXScopeSpec &SS) {
  905. if (!AnnotationPtr) {
  906. SS.SetInvalid(AnnotationRange);
  907. return;
  908. }
  909. NestedNameSpecifierAnnotation *Annotation
  910. = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
  911. SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
  912. }
  913. bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
  914. assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
  915. // Don't enter a declarator context when the current context is an Objective-C
  916. // declaration.
  917. if (isa<ObjCContainerDecl>(CurContext) || isa<ObjCMethodDecl>(CurContext))
  918. return false;
  919. NestedNameSpecifier *Qualifier = SS.getScopeRep();
  920. // There are only two places a well-formed program may qualify a
  921. // declarator: first, when defining a namespace or class member
  922. // out-of-line, and second, when naming an explicitly-qualified
  923. // friend function. The latter case is governed by
  924. // C++03 [basic.lookup.unqual]p10:
  925. // In a friend declaration naming a member function, a name used
  926. // in the function declarator and not part of a template-argument
  927. // in a template-id is first looked up in the scope of the member
  928. // function's class. If it is not found, or if the name is part of
  929. // a template-argument in a template-id, the look up is as
  930. // described for unqualified names in the definition of the class
  931. // granting friendship.
  932. // i.e. we don't push a scope unless it's a class member.
  933. switch (Qualifier->getKind()) {
  934. case NestedNameSpecifier::Global:
  935. case NestedNameSpecifier::Namespace:
  936. case NestedNameSpecifier::NamespaceAlias:
  937. // These are always namespace scopes. We never want to enter a
  938. // namespace scope from anything but a file context.
  939. return CurContext->getRedeclContext()->isFileContext();
  940. case NestedNameSpecifier::Identifier:
  941. case NestedNameSpecifier::TypeSpec:
  942. case NestedNameSpecifier::TypeSpecWithTemplate:
  943. case NestedNameSpecifier::Super:
  944. // These are never namespace scopes.
  945. return true;
  946. }
  947. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  948. }
  949. /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
  950. /// scope or nested-name-specifier) is parsed, part of a declarator-id.
  951. /// After this method is called, according to [C++ 3.4.3p3], names should be
  952. /// looked up in the declarator-id's scope, until the declarator is parsed and
  953. /// ActOnCXXExitDeclaratorScope is called.
  954. /// The 'SS' should be a non-empty valid CXXScopeSpec.
  955. bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
  956. assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
  957. if (SS.isInvalid()) return true;
  958. DeclContext *DC = computeDeclContext(SS, true);
  959. if (!DC) return true;
  960. // Before we enter a declarator's context, we need to make sure that
  961. // it is a complete declaration context.
  962. if (!DC->isDependentContext() && RequireCompleteDeclContext(SS, DC))
  963. return true;
  964. EnterDeclaratorContext(S, DC);
  965. // Rebuild the nested name specifier for the new scope.
  966. if (DC->isDependentContext())
  967. RebuildNestedNameSpecifierInCurrentInstantiation(SS);
  968. return false;
  969. }
  970. /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
  971. /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
  972. /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
  973. /// Used to indicate that names should revert to being looked up in the
  974. /// defining scope.
  975. void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
  976. assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
  977. if (SS.isInvalid())
  978. return;
  979. assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
  980. "exiting declarator scope we never really entered");
  981. ExitDeclaratorContext(S);
  982. }