name_lookup.cpp 24 KB

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