name_lookup.cpp 24 KB

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