name_lookup.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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.insts().TryGetAs<SemIR::ClassType>(
  200. context.constant_values().GetInstId(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.insts().Is<SemIR::FacetType>(
  283. context.constant_values().GetInstId(self_type_const_id))) {
  284. // We are looking directly in a facet type, like `I.F` for an interface `I`,
  285. // which means there is no self-type from the lookup for the
  286. // interface-with-self specific. So the self-type we use is the abstract
  287. // symbolic Self from the self specific of the interface-with-self.
  288. auto self_specific_args_id = context.specifics().GetArgsOrEmpty(
  289. context.generics().GetSelfSpecific(generic_with_self_id));
  290. auto self_specific_args = context.inst_blocks().Get(self_specific_args_id);
  291. return context.constant_values().Get(self_specific_args.back());
  292. }
  293. // Extended name lookup into a type, like `x.F`, can find a facet
  294. // type extended scope from the type of `x`. The type of `x` maybe a
  295. // facet converted to a type, so drop the `as type` conversion if
  296. // so.
  297. auto canonical_facet_or_type =
  298. GetCanonicalFacetOrTypeValue(context, self_type_const_id);
  299. auto type_of_canonical_facet_or_type =
  300. context.insts()
  301. .Get(context.constant_values().GetInstId(canonical_facet_or_type))
  302. .type_id();
  303. if (type_of_canonical_facet_or_type == SemIR::TypeType::TypeId) {
  304. // If we still have a type, turn it into a facet for use in the
  305. // interface-with-self specific.
  306. return GetConstantFacetValueForType(
  307. context, context.types().GetAsTypeInstId(
  308. context.constant_values().GetInstId(self_type_const_id)));
  309. }
  310. // We have a facet for the self-type (or perhaps an ErrorInst), which we can
  311. // use directly in the interface-with-self specific.
  312. return canonical_facet_or_type;
  313. }
  314. auto AppendLookupScopesForConstant(Context& context, SemIR::LocId loc_id,
  315. SemIR::ConstantId lookup_const_id,
  316. SemIR::ConstantId self_type_const_id,
  317. llvm::SmallVector<LookupScope>* scopes)
  318. -> bool {
  319. auto lookup_inst_id = context.constant_values().GetInstId(lookup_const_id);
  320. auto lookup = context.insts().Get(lookup_inst_id);
  321. if (auto ns = lookup.TryAs<SemIR::Namespace>()) {
  322. scopes->push_back(LookupScope{.name_scope_id = ns->name_scope_id,
  323. .specific_id = SemIR::SpecificId::None,
  324. .self_const_id = SemIR::ConstantId::None});
  325. return true;
  326. }
  327. if (auto class_ty = lookup.TryAs<SemIR::ClassType>()) {
  328. // TODO: Allow name lookup into classes that are being defined even if they
  329. // are not complete.
  330. RequireCompleteType(
  331. context, context.types().GetTypeIdForTypeConstantId(lookup_const_id),
  332. loc_id, [&] {
  333. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteClassScope, Error,
  334. "member access into incomplete class {0}",
  335. InstIdAsType);
  336. return context.emitter().Build(
  337. loc_id, QualifiedExprInIncompleteClassScope, lookup_inst_id);
  338. });
  339. auto& class_info = context.classes().Get(class_ty->class_id);
  340. scopes->push_back(LookupScope{.name_scope_id = class_info.scope_id,
  341. .specific_id = class_ty->specific_id,
  342. .self_const_id = self_type_const_id});
  343. return true;
  344. }
  345. // Extended scopes may point to a FacetType.
  346. if (auto facet_type = lookup.TryAs<SemIR::FacetType>()) {
  347. // TODO: Allow name lookup into facet types that are being defined even if
  348. // they are not complete.
  349. if (RequireCompleteType(
  350. context,
  351. context.types().GetTypeIdForTypeConstantId(lookup_const_id), loc_id,
  352. [&] {
  353. CARBON_DIAGNOSTIC(QualifiedExprInIncompleteFacetTypeScope, Error,
  354. "member access into incomplete facet type {0}",
  355. InstIdAsType);
  356. return context.emitter().Build(
  357. loc_id, QualifiedExprInIncompleteFacetTypeScope,
  358. lookup_inst_id);
  359. })) {
  360. auto facet_type_info =
  361. context.facet_types().Get(facet_type->facet_type_id);
  362. // Name lookup into "extend" constraints but not "self impls" constraints.
  363. for (const auto& extend : facet_type_info.extend_constraints) {
  364. auto& interface = context.interfaces().Get(extend.interface_id);
  365. // We need to build the inner interface-with-self specific. To do that
  366. // we need to determine the self facet value to use.
  367. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  368. context, interface.generic_with_self_id, self_type_const_id);
  369. auto interface_with_self_specific_id = MakeSpecificWithInnerSelf(
  370. context, loc_id, interface.generic_id,
  371. interface.generic_with_self_id, extend.specific_id, self_facet);
  372. scopes->push_back({.name_scope_id = interface.scope_with_self_id,
  373. .specific_id = interface_with_self_specific_id,
  374. .self_const_id = self_type_const_id});
  375. }
  376. for (const auto& extend : facet_type_info.extend_named_constraints) {
  377. auto& constraint =
  378. context.named_constraints().Get(extend.named_constraint_id);
  379. // We need to build the inner constraint-with-self specific. To do that
  380. // we need to determine the self facet value to use.
  381. auto self_facet = GetSelfFacetForInterfaceFromLookupSelfType(
  382. context, constraint.generic_with_self_id, self_type_const_id);
  383. auto constraint_with_self_specific_id = MakeSpecificWithInnerSelf(
  384. context, loc_id, constraint.generic_id,
  385. constraint.generic_with_self_id, extend.specific_id, self_facet);
  386. scopes->push_back({.name_scope_id = constraint.scope_with_self_id,
  387. .specific_id = constraint_with_self_specific_id,
  388. .self_const_id = self_type_const_id});
  389. }
  390. } else {
  391. // Lookup into this scope should fail without producing an error since
  392. // `RequireCompleteFacetType` has already issued a diagnostic.
  393. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  394. .specific_id = SemIR::SpecificId::None,
  395. .self_const_id = SemIR::ConstantId::None});
  396. }
  397. return true;
  398. }
  399. if (lookup_const_id == SemIR::ErrorInst::ConstantId) {
  400. // Lookup into this scope should fail without producing an error.
  401. scopes->push_back(LookupScope{.name_scope_id = SemIR::NameScopeId::None,
  402. .specific_id = SemIR::SpecificId::None,
  403. .self_const_id = SemIR::ConstantId::None});
  404. return true;
  405. }
  406. // TODO: Per the design, if `base_id` is any kind of type, then lookup should
  407. // treat it as a name scope, even if it doesn't have members. For example,
  408. // `(i32*).X` should fail because there's no name `X` in `i32*`, not because
  409. // there's no name `X` in `type`.
  410. return false;
  411. }
  412. // Prints a diagnostic for a missing qualified name.
  413. static auto DiagnoseMemberNameNotFound(
  414. Context& context, SemIR::LocId loc_id, SemIR::NameId name_id,
  415. llvm::ArrayRef<LookupScope> lookup_scopes) -> void {
  416. if (lookup_scopes.size() == 1 &&
  417. lookup_scopes.front().name_scope_id.has_value()) {
  418. if (auto specific_id = lookup_scopes.front().specific_id;
  419. specific_id.has_value()) {
  420. CARBON_DIAGNOSTIC(MemberNameNotFoundInSpecificScope, Error,
  421. "member name `{0}` not found in {1}", SemIR::NameId,
  422. SemIR::SpecificId);
  423. context.emitter().Emit(loc_id, MemberNameNotFoundInSpecificScope, name_id,
  424. specific_id);
  425. } else {
  426. auto scope_inst_id = context.name_scopes()
  427. .Get(lookup_scopes.front().name_scope_id)
  428. .inst_id();
  429. CARBON_DIAGNOSTIC(MemberNameNotFoundInInstScope, Error,
  430. "member name `{0}` not found in {1}", SemIR::NameId,
  431. InstIdAsType);
  432. context.emitter().Emit(loc_id, MemberNameNotFoundInInstScope, name_id,
  433. scope_inst_id);
  434. }
  435. return;
  436. }
  437. CARBON_DIAGNOSTIC(MemberNameNotFound, Error, "member name `{0}` not found",
  438. SemIR::NameId);
  439. context.emitter().Emit(loc_id, MemberNameNotFound, name_id);
  440. }
  441. auto LookupQualifiedName(Context& context, SemIR::LocId loc_id,
  442. SemIR::NameId name_id,
  443. llvm::ArrayRef<LookupScope> lookup_scopes,
  444. bool required, std::optional<AccessInfo> access_info)
  445. -> LookupResult {
  446. llvm::SmallVector<LookupScope> scopes(lookup_scopes);
  447. // TODO: Support reporting of multiple prohibited access.
  448. llvm::SmallVector<ProhibitedAccessInfo> prohibited_accesses;
  449. LookupResult result = {
  450. .specific_id = SemIR::SpecificId::None,
  451. .scope_result = SemIR::ScopeLookupResult::MakeNotFound()};
  452. auto parent_const_id = SemIR::ConstantId::None;
  453. bool has_error = false;
  454. bool is_parent_access = false;
  455. // Walk this scope and, if nothing is found here, the scopes it extends.
  456. while (!scopes.empty()) {
  457. auto [scope_id, specific_id, self_const_id] = scopes.pop_back_val();
  458. if (!scope_id.has_value()) {
  459. has_error = true;
  460. continue;
  461. }
  462. auto& name_scope = context.name_scopes().Get(scope_id);
  463. has_error |= name_scope.has_error();
  464. const SemIR::ScopeLookupResult scope_result =
  465. LookupNameInExactScope(context, loc_id, name_id, scope_id, name_scope);
  466. SemIR::AccessKind access_kind = scope_result.access_kind();
  467. if (is_parent_access && scope_result.is_found() &&
  468. !access_info.has_value()) {
  469. access_info =
  470. AccessInfo{.constant_id = parent_const_id,
  471. .highest_allowed_access = SemIR::AccessKind::Protected};
  472. }
  473. auto is_access_prohibited =
  474. IsAccessProhibited(access_info, access_kind, is_parent_access);
  475. // Keep track of prohibited accesses, this will be useful for reporting
  476. // multiple prohibited accesses if we can't find a suitable lookup.
  477. if (is_access_prohibited) {
  478. prohibited_accesses.push_back({
  479. .scope_result_id = scope_result.target_inst_id(),
  480. .access_kind = access_kind,
  481. .is_parent_access = is_parent_access,
  482. });
  483. }
  484. if (!scope_result.is_found() || is_access_prohibited) {
  485. // If nothing is found in this scope or if we encountered an invalid
  486. // access, look in its extended scopes.
  487. const auto& extended = name_scope.extended_scopes();
  488. scopes.reserve(scopes.size() + extended.size());
  489. for (auto extended_id : llvm::reverse(extended)) {
  490. // Substitute into the constant describing the extended scope to
  491. // determine its corresponding specific.
  492. CARBON_CHECK(extended_id.has_value());
  493. LoadImportRef(context, extended_id);
  494. SemIR::ConstantId const_id = GetConstantValueInSpecific(
  495. context.sem_ir(), specific_id, extended_id);
  496. if (!AppendLookupScopesForConstant(context, loc_id, const_id,
  497. self_const_id, &scopes)) {
  498. // TODO: Handle case where we have a symbolic type and instead should
  499. // look in its type.
  500. }
  501. }
  502. is_parent_access |= !extended.empty();
  503. parent_const_id = context.constant_values().Get(name_scope.inst_id());
  504. continue;
  505. }
  506. // If this is our second lookup result, diagnose an ambiguity.
  507. if (result.scope_result.is_found()) {
  508. CARBON_DIAGNOSTIC(
  509. NameAmbiguousDueToExtend, Error,
  510. "ambiguous use of name `{0}` found in multiple extended scopes",
  511. SemIR::NameId);
  512. context.emitter().Emit(loc_id, NameAmbiguousDueToExtend, name_id);
  513. // TODO: Add notes pointing to the scopes.
  514. return {.specific_id = SemIR::SpecificId::None,
  515. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  516. }
  517. result.scope_result = scope_result;
  518. result.specific_id = specific_id;
  519. }
  520. if ((!prohibited_accesses.empty() || required) &&
  521. !result.scope_result.is_found()) {
  522. if (!has_error) {
  523. if (prohibited_accesses.empty()) {
  524. DiagnoseMemberNameNotFound(context, loc_id, name_id, lookup_scopes);
  525. } else {
  526. // TODO: We should report multiple prohibited accesses in case we don't
  527. // find a valid lookup. Reporting the last one should suffice for now.
  528. auto [scope_result_id, access_kind, is_parent_access] =
  529. prohibited_accesses.back();
  530. // Note, `access_info` is guaranteed to have a value here, since
  531. // `prohibited_accesses` is non-empty.
  532. DiagnoseInvalidQualifiedNameAccess(
  533. context, loc_id, SemIR::LocId(scope_result_id), name_id,
  534. access_kind, is_parent_access, *access_info);
  535. }
  536. }
  537. CARBON_CHECK(!result.scope_result.is_poisoned());
  538. return {.specific_id = SemIR::SpecificId::None,
  539. .scope_result = SemIR::ScopeLookupResult::MakeError()};
  540. }
  541. return result;
  542. }
  543. // Returns a `Core.<qualifiers>` name for diagnostics.
  544. static auto GetCoreQualifiedName(llvm::ArrayRef<CoreIdentifier> qualifiers)
  545. -> std::string {
  546. RawStringOstream str;
  547. str << "Core";
  548. for (auto qualifier : qualifiers) {
  549. str << "." << qualifier;
  550. }
  551. return str.TakeStr();
  552. }
  553. // Returns the scope of the Core package, or `None` if it's not found.
  554. //
  555. // TODO: Consider tracking the Core package in SemIR so we don't need to use
  556. // name lookup to find it.
  557. static auto GetCorePackage(Context& context, SemIR::LocId loc_id,
  558. llvm::ArrayRef<CoreIdentifier> qualifiers)
  559. -> SemIR::NameScopeId {
  560. if (context.name_scopes().IsCorePackage(SemIR::NameScopeId::Package)) {
  561. return SemIR::NameScopeId::Package;
  562. }
  563. // Look up `package.Core`.
  564. auto core_scope_result = LookupNameInExactScope(
  565. context, loc_id, SemIR::NameId::Core, SemIR::NameScopeId::Package,
  566. context.name_scopes().Get(SemIR::NameScopeId::Package));
  567. if (core_scope_result.is_found()) {
  568. // We expect it to be a namespace.
  569. if (auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(
  570. core_scope_result.target_inst_id())) {
  571. // TODO: Decide whether to allow the case where `Core` is not a package.
  572. return namespace_inst->name_scope_id;
  573. }
  574. }
  575. CARBON_DIAGNOSTIC(
  576. CoreNotFound, Error,
  577. "`{0}` implicitly referenced here, but package `Core` not found",
  578. std::string);
  579. context.emitter().Emit(loc_id, CoreNotFound,
  580. GetCoreQualifiedName(qualifiers));
  581. return SemIR::NameScopeId::None;
  582. }
  583. auto LookupNameInCore(Context& context, SemIR::LocId loc_id,
  584. llvm::ArrayRef<CoreIdentifier> qualifiers)
  585. -> SemIR::InstId {
  586. CARBON_CHECK(!qualifiers.empty());
  587. auto core_package_id = GetCorePackage(context, loc_id, qualifiers);
  588. if (!core_package_id.has_value()) {
  589. return SemIR::ErrorInst::InstId;
  590. }
  591. auto inst_id = SemIR::InstId::None;
  592. for (auto qualifier : qualifiers) {
  593. auto name_id = context.core_identifiers().AddNameId(qualifier);
  594. auto scope_id = SemIR::NameScopeId::None;
  595. if (inst_id.has_value()) {
  596. auto namespace_inst = context.insts().TryGetAs<SemIR::Namespace>(inst_id);
  597. if (namespace_inst) {
  598. scope_id = namespace_inst->name_scope_id;
  599. }
  600. } else {
  601. scope_id = core_package_id;
  602. }
  603. auto scope_result =
  604. scope_id.has_value()
  605. ? LookupNameInExactScope(context, loc_id, name_id, scope_id,
  606. context.name_scopes().Get(scope_id))
  607. : SemIR::ScopeLookupResult::MakeNotFound();
  608. if (!scope_result.is_found()) {
  609. CARBON_DIAGNOSTIC(CoreNameNotFound, Error,
  610. "name `{0}` implicitly referenced here, but not found",
  611. std::string);
  612. context.emitter().Emit(loc_id, CoreNameNotFound,
  613. GetCoreQualifiedName(qualifiers));
  614. return SemIR::ErrorInst::InstId;
  615. }
  616. // Look through import_refs and aliases.
  617. inst_id = context.constant_values().GetConstantInstId(
  618. scope_result.target_inst_id());
  619. }
  620. return inst_id;
  621. }
  622. auto DiagnoseDuplicateName(Context& context, SemIR::NameId name_id,
  623. SemIR::LocId dup_def, SemIR::LocId prev_def)
  624. -> void {
  625. CARBON_DIAGNOSTIC(NameDeclDuplicate, Error,
  626. "duplicate name `{0}` being declared in the same scope",
  627. SemIR::NameId);
  628. CARBON_DIAGNOSTIC(NameDeclPrevious, Note, "name is previously declared here");
  629. context.emitter()
  630. .Build(dup_def, NameDeclDuplicate, name_id)
  631. .Note(prev_def, NameDeclPrevious)
  632. .Emit();
  633. }
  634. auto DiagnosePoisonedName(Context& context, SemIR::NameId name_id,
  635. SemIR::LocId poisoning_loc_id,
  636. SemIR::LocId decl_name_loc_id) -> void {
  637. CARBON_CHECK(poisoning_loc_id.has_value(),
  638. "Trying to diagnose poisoned name with no poisoning location");
  639. CARBON_DIAGNOSTIC(NameUseBeforeDecl, Error,
  640. "name `{0}` used before it was declared", SemIR::NameId);
  641. CARBON_DIAGNOSTIC(NameUseBeforeDeclNote, Note, "declared here");
  642. context.emitter()
  643. .Build(poisoning_loc_id, NameUseBeforeDecl, name_id)
  644. .Note(decl_name_loc_id, NameUseBeforeDeclNote)
  645. .Emit();
  646. }
  647. auto DiagnoseNameNotFound(Context& context, SemIR::LocId loc_id,
  648. SemIR::NameId name_id) -> void {
  649. CARBON_DIAGNOSTIC(NameNotFound, Error, "name `{0}` not found", SemIR::NameId);
  650. context.emitter().Emit(loc_id, NameNotFound, name_id);
  651. }
  652. } // namespace Carbon::Check