name_lookup.cpp 24 KB

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