name_lookup.cpp 25 KB

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