name_lookup.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/name_lookup.h"
  5. #include <optional>
  6. #include "common/raw_string_ostream.h"
  7. #include "toolchain/check/control_flow.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/facet_type.h"
  10. #include "toolchain/check/generic.h"
  11. #include "toolchain/check/import.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/member_access.h"
  15. #include "toolchain/check/subst.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/diagnostics/format_providers.h"
  19. #include "toolchain/sem_ir/generic.h"
  20. #include "toolchain/sem_ir/ids.h"
  21. #include "toolchain/sem_ir/name_scope.h"
  22. namespace Carbon::Check {
  23. auto AddNameToLookup(Context& context, SemIR::NameId name_id,
  24. SemIR::InstId target_id, ScopeIndex scope_index) -> void {
  25. if (auto existing = context.scope_stack().LookupOrAddName(
  26. name_id, target_id, scope_index, IsCurrentPositionReachable(context));
  27. existing.has_value()) {
  28. // TODO: Add coverage to this use case and use the location of the name
  29. // instead of the target.
  30. DiagnoseDuplicateName(context, name_id, SemIR::LocId(target_id),
  31. SemIR::LocId(existing));
  32. }
  33. }
  34. auto LookupNameInDecl(Context& context, SemIR::LocId loc_id,
  35. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  36. ScopeIndex scope_index) -> SemIR::ScopeLookupResult {
  37. if (!scope_id.has_value()) {
  38. // Look for a name in the specified scope or a scope nested within it only.
  39. // There are two cases where the name would be in an outer scope:
  40. //
  41. // - The name is the sole component of the declared name:
  42. //
  43. // class A;
  44. // fn F() {
  45. // class A;
  46. // }
  47. //
  48. // In this case, the inner A is not the same class as the outer A, so
  49. // lookup should not find the outer A.
  50. //
  51. // - The name is a qualifier of some larger declared name:
  52. //
  53. // class A { class B; }
  54. // fn F() {
  55. // class A.B {}
  56. // }
  57. //
  58. // In this case, we're not in the correct scope to define a member of
  59. // class A, so we should reject, and we achieve this by not finding the
  60. // name A from the outer scope.
  61. //
  62. // There is also one case where the name would be in an inner scope:
  63. //
  64. // - The name is redeclared by a parameter of the same entity:
  65. //
  66. // fn F() {
  67. // class C(C:! type);
  68. // }
  69. //
  70. // In this case, the class C is not a redeclaration of its parameter, but
  71. // we find the parameter in order to diagnose a redeclaration error.
  72. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  73. context.scope_stack().LookupInLexicalScopesWithin(
  74. name_id, scope_index, /*use_loc_id=*/SemIR::LocId::None,
  75. /*is_reachable=*/true),
  76. SemIR::AccessKind::Public);
  77. } else {
  78. // We do not look into `extend`ed scopes here. A qualified name in a
  79. // declaration must specify the exact scope in which the name was originally
  80. // introduced:
  81. //
  82. // base class A { fn F(); }
  83. // class B { extend base: A; }
  84. //
  85. // // Error, no `F` in `B`.
  86. // fn B.F() {}
  87. return LookupNameInExactScope(context, loc_id, name_id, scope_id,
  88. context.name_scopes().Get(scope_id),
  89. /*is_being_declared=*/true);
  90. }
  91. }
  92. auto LookupUnqualifiedName(Context& context, SemIR::LocId loc_id,
  93. SemIR::NameId name_id, bool required)
  94. -> LookupResult {
  95. // TODO: Check for shadowed lookup results.
  96. // Find the results from ancestor lexical scopes. These will be combined with
  97. // results from non-lexical scopes such as namespaces and classes.
  98. auto [lexical_result, non_lexical_scopes] =
  99. context.scope_stack().LookupInLexicalScopes(
  100. name_id, loc_id, IsCurrentPositionReachable(context));
  101. // Walk the non-lexical scopes and perform lookups into each of them.
  102. for (auto [index, lookup_scope_id, specific_id] :
  103. llvm::reverse(non_lexical_scopes)) {
  104. if (auto non_lexical_result = LookupQualifiedName(
  105. context, loc_id, name_id,
  106. LookupScope{.name_scope_id = lookup_scope_id,
  107. .specific_id = specific_id,
  108. // A non-lexical lookup does not know what `Self` will
  109. // be; it remains symbolic if needed.
  110. .self_const_id = SemIR::ConstantId::None},
  111. /*required=*/false);
  112. non_lexical_result.scope_result.is_found()) {
  113. // In an interface definition, replace associated entity `M` with
  114. // `Self.M` (where the `Self` is the `Self` of the interface).
  115. const auto& scope = context.name_scopes().Get(lookup_scope_id);
  116. if (scope.is_interface_definition()) {
  117. SemIR::InstId target_inst_id =
  118. non_lexical_result.scope_result.target_inst_id();
  119. if (auto assoc_type =
  120. context.types().TryGetAs<SemIR::AssociatedEntityType>(
  121. SemIR::GetTypeOfInstInSpecific(
  122. context.sem_ir(), non_lexical_result.specific_id,
  123. target_inst_id))) {
  124. auto interface_decl =
  125. context.insts().GetAs<SemIR::InterfaceWithSelfDecl>(
  126. scope.inst_id());
  127. const auto& interface =
  128. context.interfaces().Get(interface_decl.interface_id);
  129. SemIR::InstId result_inst_id = GetAssociatedValue(
  130. context, loc_id, interface.self_param_id,
  131. SemIR::GetConstantValueInSpecific(context.sem_ir(),
  132. non_lexical_result.specific_id,
  133. target_inst_id),
  134. assoc_type->GetSpecificInterface());
  135. non_lexical_result = {
  136. .specific_id = SemIR::SpecificId::None,
  137. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  138. result_inst_id,
  139. non_lexical_result.scope_result.access_kind())};
  140. }
  141. }
  142. return non_lexical_result;
  143. }
  144. }
  145. if (lexical_result == SemIR::InstId::InitTombstone) {
  146. CARBON_DIAGNOSTIC(UsedBeforeInitialization, Error,
  147. "`{0}` used before initialization", SemIR::NameId);
  148. context.emitter().Emit(loc_id, UsedBeforeInitialization, name_id);
  149. return {.specific_id = SemIR::SpecificId::None,
  150. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  151. }
  152. if (lexical_result.has_value()) {
  153. // A lexical scope never needs an associated specific. If there's a
  154. // lexically enclosing generic, then it also encloses the point of use of
  155. // the name.
  156. return {.specific_id = SemIR::SpecificId::None,
  157. .scope_result = SemIR::ScopeLookupResult::MakeFound(
  158. lexical_result, SemIR::AccessKind::Public)};
  159. }
  160. // We didn't find anything at all.
  161. if (required) {
  162. DiagnoseNameNotFound(context, loc_id, name_id);
  163. }
  164. // TODO: Should this return MakeNotFound if `required` is false, so that
  165. // `is_found()` would be false?
  166. return {.specific_id = SemIR::SpecificId::None,
  167. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  168. }
  169. auto LookupNameInExactScope(Context& context, SemIR::LocId loc_id,
  170. SemIR::NameId name_id, SemIR::NameScopeId scope_id,
  171. SemIR::NameScope& scope, bool is_being_declared)
  172. -> SemIR::ScopeLookupResult {
  173. if (auto entry_id = is_being_declared
  174. ? scope.Lookup(name_id)
  175. : scope.LookupOrPoison(loc_id, name_id)) {
  176. auto lookup_result = scope.GetEntry(*entry_id).result;
  177. if (!lookup_result.is_poisoned()) {
  178. LoadImportRef(context, lookup_result.target_inst_id());
  179. }
  180. return lookup_result;
  181. }
  182. if (!scope.import_ir_scopes().empty()) {
  183. // TODO: Enforce other access modifiers for imports.
  184. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  185. ImportNameFromOtherPackage(context, loc_id, scope_id,
  186. scope.import_ir_scopes(), name_id),
  187. SemIR::AccessKind::Public);
  188. }
  189. if (scope.is_cpp_scope()) {
  190. return ImportNameFromCpp(context, loc_id, scope_id, name_id);
  191. }
  192. return SemIR::ScopeLookupResult::MakeNotFound();
  193. }
  194. // Prints diagnostics on invalid qualified name access.
  195. static auto DiagnoseInvalidQualifiedNameAccess(
  196. Context& context, SemIR::LocId loc_id, SemIR::LocId member_loc_id,
  197. SemIR::NameId name_id, SemIR::AccessKind access_kind, bool is_parent_access,
  198. AccessInfo access_info) -> void {
  199. auto class_type = context.constant_values().TryGetInstAs<SemIR::ClassType>(
  200. access_info.constant_id);
  201. if (!class_type) {
  202. return;
  203. }
  204. // TODO: Support scoped entities other than just classes.
  205. const auto& class_info = context.classes().Get(class_type->class_id);
  206. auto parent_type_id = class_info.self_type_id;
  207. if (access_kind == SemIR::AccessKind::Private && is_parent_access) {
  208. if (auto base_type_id =
  209. class_info.GetBaseType(context.sem_ir(), class_type->specific_id);
  210. base_type_id.has_value()) {
  211. parent_type_id = base_type_id;
  212. } else if (auto adapted_type_id = class_info.GetAdaptedType(
  213. context.sem_ir(), class_type->specific_id);
  214. adapted_type_id.has_value()) {
  215. parent_type_id = adapted_type_id;
  216. } else {
  217. CARBON_FATAL("Expected parent for parent access");
  218. }
  219. }
  220. CARBON_DIAGNOSTIC(
  221. ClassInvalidMemberAccess, Error,
  222. "cannot access {0:private|protected} member `{1}` of type {2}",
  223. Diagnostics::BoolAsSelect, SemIR::NameId, SemIR::TypeId);
  224. CARBON_DIAGNOSTIC(ClassMemberDeclaration, Note, "declared here");
  225. context.emitter()
  226. .Build(loc_id, ClassInvalidMemberAccess,
  227. access_kind == SemIR::AccessKind::Private, name_id, parent_type_id)
  228. .Note(member_loc_id, ClassMemberDeclaration)
  229. .Emit();
  230. }
  231. // Returns whether the access is prohibited by the access modifiers.
  232. static auto IsAccessProhibited(std::optional<AccessInfo> access_info,
  233. SemIR::AccessKind access_kind,
  234. bool is_parent_access) -> bool {
  235. if (!access_info) {
  236. return false;
  237. }
  238. switch (access_kind) {
  239. case SemIR::AccessKind::Public:
  240. return false;
  241. case SemIR::AccessKind::Protected:
  242. return access_info->highest_allowed_access == SemIR::AccessKind::Public;
  243. case SemIR::AccessKind::Private:
  244. return access_info->highest_allowed_access !=
  245. SemIR::AccessKind::Private ||
  246. is_parent_access;
  247. }
  248. }
  249. auto CheckAccess(Context& context, SemIR::LocId loc_id,
  250. SemIR::LocId member_loc_id, SemIR::NameId name_id,
  251. SemIR::AccessKind access_kind, bool is_parent_access,
  252. AccessInfo access_info) -> void {
  253. if (IsAccessProhibited(access_info, access_kind, is_parent_access)) {
  254. DiagnoseInvalidQualifiedNameAccess(context, loc_id, member_loc_id, name_id,
  255. access_kind, is_parent_access,
  256. access_info);
  257. }
  258. }
  259. // Information regarding a prohibited access.
  260. struct ProhibitedAccessInfo {
  261. // The resulting inst of the lookup.
  262. SemIR::InstId scope_result_id;
  263. // The access kind of the lookup.
  264. SemIR::AccessKind access_kind;
  265. // If the lookup is from an extended scope. For example, if this is a base
  266. // class member access from a class that extends it.
  267. bool is_parent_access;
  268. };
  269. static auto GetSelfFacetForInterfaceFromLookupSelfType(
  270. Context& context, const SemIR::GenericId generic_with_self_id,
  271. SemIR::ConstantId self_type_const_id) -> SemIR::ConstantId {
  272. if (!self_type_const_id.has_value()) {
  273. // In a lookup into a non-lexical scope, there is no self-type from the
  274. // lookup for the interface-with-self specific. So the self-type we use is
  275. // the abstract symbolic Self from the self specific of the
  276. // interface-with-self.
  277. auto self_specific_args_id = context.specifics().GetArgsOrEmpty(
  278. context.generics().GetSelfSpecific(generic_with_self_id));
  279. auto self_specific_args = context.inst_blocks().Get(self_specific_args_id);
  280. return context.constant_values().Get(self_specific_args.back());
  281. }
  282. if (context.constant_values().InstIs<SemIR::FacetType>(self_type_const_id)) {
  283. // We are looking directly in a facet type, like `I.F` for an interface `I`,
  284. // which means there is no self-type from the lookup for the
  285. // interface-with-self specific. So the self-type we use is the abstract
  286. // symbolic Self from the self specific of the interface-with-self.
  287. auto self_specific_args_id = context.specifics().GetArgsOrEmpty(
  288. context.generics().GetSelfSpecific(generic_with_self_id));
  289. auto self_specific_args = context.inst_blocks().Get(self_specific_args_id);
  290. return context.constant_values().Get(self_specific_args.back());
  291. }
  292. // Extended name lookup into a type, like `x.F`, can find a facet
  293. // type extended scope from the type of `x`. The type of `x` maybe a
  294. // facet converted to a type, so drop the `as type` conversion if
  295. // so.
  296. auto canonical_facet_or_type =
  297. GetCanonicalFacetOrTypeValue(context, self_type_const_id);
  298. auto type_of_canonical_facet_or_type =
  299. context.insts()
  300. .Get(context.constant_values().GetInstId(canonical_facet_or_type))
  301. .type_id();
  302. if (type_of_canonical_facet_or_type == SemIR::TypeType::TypeId) {
  303. // If we still have a type, turn it into a facet for use in the
  304. // interface-with-self specific.
  305. return GetConstantFacetValueForType(
  306. context, context.types().GetAsTypeInstId(
  307. context.constant_values().GetInstId(self_type_const_id)));
  308. }
  309. // We have a facet for the self-type (or perhaps an ErrorInst), which we can
  310. // use directly in the interface-with-self specific.
  311. return canonical_facet_or_type;
  312. }
  313. auto AppendLookupScopesForConstant(Context& context, SemIR::LocId loc_id,
  314. SemIR::ConstantId lookup_const_id,
  315. SemIR::ConstantId self_type_const_id,
  316. llvm::SmallVector<LookupScope>* scopes)
  317. -> bool {
  318. auto lookup_inst_id = context.constant_values().GetInstId(lookup_const_id);
  319. auto lookup = context.insts().Get(lookup_inst_id);
  320. if (auto ns = lookup.TryAs<SemIR::Namespace>()) {
  321. scopes->push_back(LookupScope{.name_scope_id = ns->name_scope_id,
  322. .specific_id = SemIR::SpecificId::None,
  323. .self_const_id = SemIR::ConstantId::None});
  324. return true;
  325. }
  326. if (auto class_ty = lookup.TryAs<SemIR::ClassType>()) {
  327. // TODO: Allow name lookup into classes that are being defined even if they
  328. // are not complete.
  329. RequireCompleteType(
  330. context, context.types().GetTypeIdForTypeConstantId(lookup_const_id),
  331. loc_id, [&](auto& builder) {
  332. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Context,
  333. "member access into incomplete class {0}",
  334. InstIdAsType);
  335. builder.Context(loc_id, QualifiedExprInIncompleteClassScope,
  336. lookup_inst_id);
  337. });
  338. auto& class_info = context.classes().Get(class_ty->class_id);
  339. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  340. .specific_id = class_ty->specific_id,
  341. .self_const_id = self_type_const_id});
  342. return true;
  343. }
  344. // Extended scopes may point to a FacetType.
  345. if (auto facet_type = lookup.TryAs<SemIR::FacetType>()) {
  346. // TODO: Allow name lookup into facet types that are being defined even if
  347. // they are not complete.
  348. if (RequireCompleteType(
  349. context,
  350. context.types().GetTypeIdForTypeConstantId(lookup_const_id), loc_id,
  351. [&](auto& builder) {
  352. CARBON_DIAGNOSTIC(
  353. QualifiedExprInIncompleteFacetTypeScope, Context,
  354. "member access into incomplete facet type {0}", InstIdAsType);
  355. builder.Context(loc_id, QualifiedExprInIncompleteFacetTypeScope,
  356. lookup_inst_id);
  357. })) {
  358. auto facet_type_info =
  359. context.facet_types().Get(facet_type->facet_type_id);
  360. // Name lookup into "extend" constraints but not "self impls" constraints.
  361. for (const auto& extend : facet_type_info.extend_constraints) {
  362. auto& interface = context.interfaces().Get(extend.interface_id);
  363. // We need to build the inner interface-with-self specific. To do that
  364. // we need to determine the self facet value to use.
  365. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  366. context, interface.generic_with_self_id, self_type_const_id);
  367. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  368. context, loc_id, interface.generic_id,
  369. interface.generic_with_self_id, extend.specific_id, self_facet);
  370. scopes->push_back({.name_scope_id = interface.scope_with_self_id,
  371. .specific_id = interface_with_self_specific_id,
  372. .self_const_id = self_type_const_id});
  373. }
  374. for (const auto& extend : facet_type_info.extend_named_constraints) {
  375. auto& constraint =
  376. context.named_constraints().Get(extend.named_constraint_id);
  377. // We need to build the inner constraint-with-self specific. To do that
  378. // we need to determine the self facet value to use.
  379. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  380. context, constraint.generic_with_self_id, self_type_const_id);
  381. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  382. context, loc_id, constraint.generic_id,
  383. constraint.generic_with_self_id, extend.specific_id, self_facet);
  384. scopes->push_back({.name_scope_id = constraint.scope_with_self_id,
  385. .specific_id = constraint_with_self_specific_id,
  386. .self_const_id = self_type_const_id});
  387. }
  388. } else {
  389. // Lookup into this scope should fail without producing an error since
  390. // `RequireCompleteFacetType` has already issued a diagnostic.
  391. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  392. .specific_id = SemIR::SpecificId::None,
  393. .self_const_id = SemIR::ConstantId::None});
  394. }
  395. return true;
  396. }
  397. if (lookup_const_id == SemIR::ErrorInst::ConstantId) {
  398. // Lookup into this scope should fail without producing an error.
  399. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  400. .specific_id = SemIR::SpecificId::None,
  401. .self_const_id = SemIR::ConstantId::None});
  402. return true;
  403. }
  404. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  405. // treat it as a name scope, even if it doesn't have members. For example,
  406. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  407. // there's no name `X` in `type`.
  408. return false;
  409. }
  410. // Prints a diagnostic for a missing qualified name.
  411. static auto DiagnoseMemberNameNotFound(
  412. Context& context, SemIR::LocId loc_id, SemIR::NameId name_id,
  413. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  414. if (lookup_scopes.size() == 1 &&
  415. lookup_scopes.front().name_scope_id.has_value()) {
  416. if (auto specific_id = lookup_scopes.front().specific_id;
  417. specific_id.has_value()) {
  418. CARBON_DIAGNOSTIC(MemberNameNotFoundInSpecificScope, Error,
  419. "member name `{0}` not found in {1}", SemIR::NameId,
  420. SemIR::SpecificId);
  421. context.emitter().Emit(loc_id, MemberNameNotFoundInSpecificScope, name_id,
  422. specific_id);
  423. } else {
  424. auto scope_inst_id = context.name_scopes()
  425. .Get(lookup_scopes.front().name_scope_id)
  426. .inst_id();
  427. CARBON_DIAGNOSTIC(MemberNameNotFoundInInstScope, Error,
  428. "member name `{0}` not found in {1}", SemIR::NameId,
  429. InstIdAsType);
  430. context.emitter().Emit(loc_id, MemberNameNotFoundInInstScope, name_id,
  431. scope_inst_id);
  432. }
  433. return;
  434. }
  435. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  436. SemIR::NameId);
  437. context.emitter().Emit(loc_id, MemberNameNotFound, name_id);
  438. }
  439. auto LookupQualifiedName(Context& context, SemIR::LocId loc_id,
  440. SemIR::NameId name_id,
  441. llvm::ArrayRef<LookupScope> lookup_scopes,
  442. bool required, std::optional<AccessInfo> access_info)
  443. -> LookupResult {
  444. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  445. // TODO: Support reporting of multiple prohibited access.
  446. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  447. LookupResult result = {
  448. .specific_id = SemIR::SpecificId::None,
  449. .scope_result = SemIR::ScopeLookupResult::MakeNotFound()};
  450. auto parent_const_id = SemIR::ConstantId::None;
  451. bool has_error = false;
  452. bool is_parent_access = false;
  453. // Walk this scope and, if nothing is found here, the scopes it extends.
  454. while (!scopes.empty()) {
  455. auto [scope_id, specific_id, self_const_id] = scopes.pop_back_val();
  456. if (!scope_id.has_value()) {
  457. has_error = true;
  458. continue;
  459. }
  460. auto& name_scope = context.name_scopes().Get(scope_id);
  461. has_error |= name_scope.has_error();
  462. const SemIR::ScopeLookupResult scope_result =
  463. LookupNameInExactScope(context, loc_id, name_id, scope_id, name_scope);
  464. SemIR::AccessKind access_kind = scope_result.access_kind();
  465. if (is_parent_access && scope_result.is_found() &&
  466. !access_info.has_value()) {
  467. access_info =
  468. AccessInfo{.constant_id = parent_const_id,
  469. .highest_allowed_access = SemIR::AccessKind::Protected};
  470. }
  471. auto is_access_prohibited =
  472. IsAccessProhibited(access_info, access_kind, is_parent_access);
  473. // Keep track of prohibited accesses, this will be useful for reporting
  474. // multiple prohibited accesses if we can't find a suitable lookup.
  475. if (is_access_prohibited) {
  476. prohibited_accesses.push_back({
  477. .scope_result_id = scope_result.target_inst_id(),
  478. .access_kind = access_kind,
  479. .is_parent_access = is_parent_access,
  480. });
  481. }
  482. if (!scope_result.is_found() || is_access_prohibited) {
  483. // If nothing is found in this scope or if we encountered an invalid
  484. // access, look in its extended scopes.
  485. const auto& extended = name_scope.extended_scopes();
  486. scopes.reserve(scopes.size() + extended.size());
  487. for (auto extended_id : llvm::reverse(extended)) {
  488. // Substitute into the constant describing the extended scope to
  489. // determine its corresponding specific.
  490. CARBON_CHECK(extended_id.has_value());
  491. LoadImportRef(context, extended_id);
  492. SemIR::ConstantId const_id = GetConstantValueInSpecific(
  493. context.sem_ir(), specific_id, extended_id);
  494. if (!AppendLookupScopesForConstant(context, loc_id, const_id,
  495. self_const_id, &scopes)) {
  496. // TODO: Handle case where we have a symbolic type and instead should
  497. // look in its type.
  498. }
  499. }
  500. is_parent_access |= !extended.empty();
  501. parent_const_id = context.constant_values().Get(name_scope.inst_id());
  502. continue;
  503. }
  504. // If this is our second lookup result, diagnose an ambiguity.
  505. if (result.scope_result.is_found()) {
  506. CARBON_DIAGNOSTIC(
  507. NameAmbiguousDueToExtend, Error,
  508. "ambiguous use of name `{0}` found in multiple extended scopes",
  509. SemIR::NameId);
  510. context.emitter().Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  511. // TODO: Add notes pointing to the scopes.
  512. return {.specific_id = SemIR::SpecificId::None,
  513. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  514. }
  515. result.scope_result = scope_result;
  516. result.specific_id = specific_id;
  517. }
  518. if ((!prohibited_accesses.empty() || required) &&
  519. !result.scope_result.is_found()) {
  520. if (!has_error) {
  521. if (prohibited_accesses.empty()) {
  522. DiagnoseMemberNameNotFound(context, loc_id, name_id, lookup_scopes);
  523. } else {
  524. // TODO: We should report multiple prohibited accesses in case we don't
  525. // find a valid lookup. Reporting the last one should suffice for now.
  526. auto [scope_result_id, access_kind, is_parent_access] =
  527. prohibited_accesses.back();
  528. // Note, `access_info` is guaranteed to have a value here, since
  529. // `prohibited_accesses` is non-empty.
  530. DiagnoseInvalidQualifiedNameAccess(
  531. context, loc_id, SemIR::LocId(scope_result_id), name_id,
  532. access_kind, is_parent_access, *access_info);
  533. }
  534. }
  535. CARBON_CHECK(!result.scope_result.is_poisoned());
  536. return {.specific_id = SemIR::SpecificId::None,
  537. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  538. }
  539. return result;
  540. }
  541. // Returns a `Core.<qualifiers>` name for diagnostics.
  542. static auto GetCoreQualifiedName(llvm::ArrayRef<CoreIdentifier> qualifiers)
  543. -> std::string {
  544. RawStringOstream str;
  545. str << "Core";
  546. for (auto qualifier : qualifiers) {
  547. str << "." << qualifier;
  548. }
  549. return str.TakeStr();
  550. }
  551. // Returns the scope of the Core package, or `None` if it's not found.
  552. //
  553. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  554. // name lookup to find it.
  555. static auto GetCorePackage(Context& context, SemIR::LocId loc_id,
  556. llvm::ArrayRef<CoreIdentifier> qualifiers)
  557. -> SemIR::NameScopeId {
  558. if (context.name_scopes().IsCorePackage(SemIR::NameScopeId::Package)) {
  559. return SemIR::NameScopeId::Package;
  560. }
  561. // Look up `package.Core`.
  562. auto core_scope_result = LookupNameInExactScope(
  563. context, loc_id, SemIR::NameId::Core, SemIR::NameScopeId::Package,
  564. context.name_scopes().Get(SemIR::NameScopeId::Package));
  565. if (core_scope_result.is_found()) {
  566. // We expect it to be a namespace.
  567. if (auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(
  568. core_scope_result.target_inst_id())) {
  569. // TODO: Decide whether to allow the case where `Core` is not a package.
  570. return namespace_inst->name_scope_id;
  571. }
  572. }
  573. CARBON_DIAGNOSTIC(
  574. CoreNotFound, Error,
  575. "`{0}` implicitly referenced here, but package `Core` not found",
  576. std::string);
  577. context.emitter().Emit(loc_id, CoreNotFound,
  578. GetCoreQualifiedName(qualifiers));
  579. return SemIR::NameScopeId::None;
  580. }
  581. auto LookupNameInCore(Context& context, SemIR::LocId loc_id,
  582. llvm::ArrayRef<CoreIdentifier> qualifiers)
  583. -> SemIR::InstId {
  584. CARBON_CHECK(!qualifiers.empty());
  585. auto core_package_id = GetCorePackage(context, loc_id, qualifiers);
  586. if (!core_package_id.has_value()) {
  587. return SemIR::ErrorInst::InstId;
  588. }
  589. auto inst_id = SemIR::InstId::None;
  590. for (auto qualifier : qualifiers) {
  591. auto name_id = context.core_identifiers().AddNameId(qualifier);
  592. auto scope_id = SemIR::NameScopeId::None;
  593. if (inst_id.has_value()) {
  594. auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(inst_id);
  595. if (namespace_inst) {
  596. scope_id = namespace_inst->name_scope_id;
  597. }
  598. } else {
  599. scope_id = core_package_id;
  600. }
  601. auto scope_result =
  602. scope_id.has_value()
  603. ? LookupNameInExactScope(context, loc_id, name_id, scope_id,
  604. context.name_scopes().Get(scope_id))
  605. : SemIR::ScopeLookupResult::MakeNotFound();
  606. if (!scope_result.is_found()) {
  607. CARBON_DIAGNOSTIC(CoreNameNotFound, Error,
  608. "name `{0}` implicitly referenced here, but not found",
  609. std::string);
  610. context.emitter().Emit(loc_id, CoreNameNotFound,
  611. GetCoreQualifiedName(qualifiers));
  612. return SemIR::ErrorInst::InstId;
  613. }
  614. // Look through import_refs and aliases.
  615. inst_id = context.constant_values().GetConstantInstId(
  616. scope_result.target_inst_id());
  617. }
  618. return inst_id;
  619. }
  620. auto DiagnoseDuplicateName(Context& context, SemIR::NameId name_id,
  621. SemIR::LocId dup_def, SemIR::LocId prev_def)
  622. -> void {
  623. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  624. "duplicate name `{0}` being declared in the same scope",
  625. SemIR::NameId);
  626. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  627. context.emitter()
  628. .Build(dup_def, NameDeclDuplicate, name_id)
  629. .Note(prev_def, NameDeclPrevious)
  630. .Emit();
  631. }
  632. auto DiagnosePoisonedName(Context& context, SemIR::NameId name_id,
  633. SemIR::LocId poisoning_loc_id,
  634. SemIR::LocId decl_name_loc_id) -> void {
  635. CARBON_CHECK(poisoning_loc_id.has_value(),
  636. "Trying to diagnose poisoned name with no poisoning location");
  637. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  638. "name `{0}` used before it was declared", SemIR::NameId);
  639. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  640. context.emitter()
  641. .Build(poisoning_loc_id, NameUseBeforeDecl, name_id)
  642. .Note(decl_name_loc_id, NameUseBeforeDeclNote)
  643. .Emit();
  644. }
  645. auto DiagnoseNameNotFound(Context& context, SemIR::LocId loc_id,
  646. SemIR::NameId name_id) -> void {
  647. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  648. context.emitter().Emit(loc_id, NameNotFound, name_id);
  649. }
  650. } // namespace Carbon::Check