import.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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/import.h"
  5. #include "common/check.h"
  6. #include "common/map.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/import_ref.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/check/name_lookup.h"
  12. #include "toolchain/check/type.h"
  13. #include "toolchain/parse/node_ids.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/import_ir.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/name_scope.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::Check {
  21. // Returns name information for an EntityWithParamsBase.
  22. template <typename T>
  23. static auto GetImportNameForEntity(const T& entity)
  24. -> std::pair<SemIR::NameId, SemIR::NameScopeId> {
  25. return {entity.name_id, entity.parent_scope_id};
  26. }
  27. template <>
  28. auto GetImportNameForEntity(const SemIR::NameScope& entity)
  29. -> std::pair<SemIR::NameId, SemIR::NameScopeId> {
  30. return {entity.name_id(), entity.parent_scope_id()};
  31. }
  32. // Returns name information for the entity, corresponding to IDs in the import
  33. // IR rather than the current IR.
  34. static auto GetImportName(const SemIR::File& import_sem_ir,
  35. SemIR::Inst import_inst)
  36. -> std::pair<SemIR::NameId, SemIR::NameScopeId> {
  37. CARBON_KIND_SWITCH(import_inst) {
  38. case SemIR::BindAlias::Kind:
  39. case SemIR::BindName::Kind:
  40. case SemIR::BindSymbolicName::Kind:
  41. case SemIR::ExportDecl::Kind: {
  42. auto bind_inst = import_inst.As<SemIR::AnyBindNameOrExportDecl>();
  43. return GetImportNameForEntity(
  44. import_sem_ir.entity_names().Get(bind_inst.entity_name_id));
  45. }
  46. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  47. return GetImportNameForEntity(
  48. import_sem_ir.classes().Get(class_decl.class_id));
  49. }
  50. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  51. return GetImportNameForEntity(
  52. import_sem_ir.functions().Get(function_decl.function_id));
  53. }
  54. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  55. return GetImportNameForEntity(
  56. import_sem_ir.interfaces().Get(interface_decl.interface_id));
  57. }
  58. case CARBON_KIND(SemIR::Namespace ns): {
  59. return GetImportNameForEntity(
  60. import_sem_ir.name_scopes().Get(ns.name_scope_id));
  61. }
  62. default:
  63. CARBON_FATAL("Unsupported export kind: {0}", import_inst);
  64. }
  65. }
  66. // Translate the name to the current IR. It will usually be an identifier, but
  67. // could also be a builtin name ID which is equivalent cross-IR.
  68. static auto CopyNameFromImportIR(Context& context,
  69. const SemIR::File& import_sem_ir,
  70. SemIR::NameId import_name_id) {
  71. if (auto import_identifier_id = import_name_id.AsIdentifierId();
  72. import_identifier_id.has_value()) {
  73. auto name = import_sem_ir.identifiers().Get(import_identifier_id);
  74. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  75. }
  76. return import_name_id;
  77. }
  78. auto AddImportNamespace(Context& context, SemIR::TypeId namespace_type_id,
  79. SemIR::NameId name_id,
  80. SemIR::NameScopeId parent_scope_id,
  81. bool diagnose_duplicate_namespace,
  82. llvm::function_ref<SemIR::InstId()> make_import_id)
  83. -> AddImportNamespaceResult {
  84. auto* parent_scope = &context.name_scopes().Get(parent_scope_id);
  85. auto [inserted, entry_id] = parent_scope->LookupOrAdd(
  86. name_id,
  87. // This InstId is temporary and would be overridden if used.
  88. SemIR::InstId::None, SemIR::AccessKind::Public);
  89. if (!inserted) {
  90. const auto& prev_entry = parent_scope->GetEntry(entry_id);
  91. if (!prev_entry.result.is_poisoned()) {
  92. auto prev_inst_id = prev_entry.result.target_inst_id();
  93. if (auto namespace_inst =
  94. context.insts().TryGetAs<SemIR::Namespace>(prev_inst_id)) {
  95. if (diagnose_duplicate_namespace) {
  96. auto import_id = make_import_id();
  97. CARBON_CHECK(import_id.has_value());
  98. DiagnoseDuplicateName(context, import_id, prev_inst_id);
  99. }
  100. return {.name_scope_id = namespace_inst->name_scope_id,
  101. .inst_id = prev_inst_id,
  102. .is_duplicate_of_namespace_in_current_package = true};
  103. }
  104. }
  105. }
  106. auto import_id = make_import_id();
  107. CARBON_CHECK(import_id.has_value());
  108. auto import_loc_id = context.insts().GetLocId(import_id);
  109. auto namespace_inst =
  110. SemIR::Namespace{.type_id = namespace_type_id,
  111. .name_scope_id = SemIR::NameScopeId::None,
  112. .import_id = import_id};
  113. auto namespace_inst_and_loc =
  114. import_loc_id.is_import_ir_inst_id()
  115. ? context.MakeImportedLocAndInst(import_loc_id.import_ir_inst_id(),
  116. namespace_inst)
  117. // TODO: Check that this actually is an `AnyNamespaceId`.
  118. : SemIR::LocIdAndInst(Parse::AnyNamespaceId(import_loc_id.node_id()),
  119. namespace_inst);
  120. auto namespace_id =
  121. context.AddPlaceholderInstInNoBlock(namespace_inst_and_loc);
  122. context.import_ref_ids().push_back(namespace_id);
  123. namespace_inst.name_scope_id =
  124. context.name_scopes().Add(namespace_id, name_id, parent_scope_id);
  125. context.ReplaceInstBeforeConstantUse(namespace_id, namespace_inst);
  126. // Note we have to get the parent scope freshly, creating the imported
  127. // namespace may invalidate the pointer above.
  128. parent_scope = &context.name_scopes().Get(parent_scope_id);
  129. // Diagnose if there's a name conflict, but still produce the namespace to
  130. // supersede the name conflict in order to avoid repeat diagnostics. Names are
  131. // poisoned optimistically by name lookup before checking for imports, so we
  132. // may be overwriting a poisoned entry here.
  133. auto& result = parent_scope->GetEntry(entry_id).result;
  134. if (!result.is_poisoned() && !inserted) {
  135. DiagnoseDuplicateName(context, namespace_id, result.target_inst_id());
  136. }
  137. result = SemIR::ScopeLookupResult::MakeFound(namespace_id,
  138. SemIR::AccessKind::Public);
  139. return {.name_scope_id = namespace_inst.name_scope_id,
  140. .inst_id = namespace_id,
  141. .is_duplicate_of_namespace_in_current_package = false};
  142. }
  143. // Adds a copied namespace to the cache.
  144. static auto CacheCopiedNamespace(
  145. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces,
  146. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId to_scope_id)
  147. -> void {
  148. auto result = copied_namespaces.Insert(import_scope_id, to_scope_id);
  149. CARBON_CHECK(result.is_inserted() || result.value() == to_scope_id,
  150. "Copy result for namespace changed from {0} to {1}",
  151. import_scope_id, to_scope_id);
  152. }
  153. // Copies a namespace from the import IR, returning its ID. This may diagnose
  154. // name conflicts, but that won't change the result because namespaces supersede
  155. // other names in conflicts. The bool on return is true if there was a name
  156. // conflict. copied_namespaces is optional.
  157. static auto CopySingleNameScopeFromImportIR(
  158. Context& context, SemIR::TypeId namespace_type_id,
  159. Map<SemIR::NameScopeId, SemIR::NameScopeId>* copied_namespaces,
  160. SemIR::ImportIRId ir_id, SemIR::InstId import_inst_id,
  161. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId parent_scope_id,
  162. SemIR::NameId name_id) -> AddImportNamespaceResult {
  163. // Produce the namespace for the entry.
  164. auto make_import_id = [&]() {
  165. auto entity_name_id = context.entity_names().Add(
  166. {.name_id = name_id, .parent_scope_id = parent_scope_id});
  167. auto import_ir_inst_id = context.import_ir_insts().Add(
  168. {.ir_id = ir_id, .inst_id = import_inst_id});
  169. auto inst_id = context.AddInstInNoBlock(
  170. context.MakeImportedLocAndInst<SemIR::ImportRefLoaded>(
  171. import_ir_inst_id, {.type_id = namespace_type_id,
  172. .import_ir_inst_id = import_ir_inst_id,
  173. .entity_name_id = entity_name_id}));
  174. context.import_ref_ids().push_back(inst_id);
  175. return inst_id;
  176. };
  177. AddImportNamespaceResult result = AddImportNamespace(
  178. context, namespace_type_id, name_id, parent_scope_id,
  179. /*diagnose_duplicate_namespace=*/false, make_import_id);
  180. auto namespace_const_id = context.constant_values().Get(result.inst_id);
  181. context.import_ir_constant_values()[ir_id.index].Set(import_inst_id,
  182. namespace_const_id);
  183. if (copied_namespaces) {
  184. CacheCopiedNamespace(*copied_namespaces, import_scope_id,
  185. result.name_scope_id);
  186. }
  187. return result;
  188. }
  189. // Copies ancestor name scopes from the import IR. Handles the parent traversal.
  190. // Returns the NameScope corresponding to the copied import_parent_scope_id.
  191. static auto CopyAncestorNameScopesFromImportIR(
  192. Context& context, SemIR::TypeId namespace_type_id,
  193. const SemIR::File& import_sem_ir, SemIR::ImportIRId ir_id,
  194. SemIR::NameScopeId import_parent_scope_id,
  195. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces)
  196. -> SemIR::NameScopeId {
  197. // Package-level names don't need work.
  198. if (import_parent_scope_id == SemIR::NameScopeId::Package) {
  199. return import_parent_scope_id;
  200. }
  201. // The scope to add namespaces to. Note this may change while looking at
  202. // parent scopes, if we encounter a namespace that's already added.
  203. auto scope_cursor = SemIR::NameScopeId::Package;
  204. // Build a stack of ancestor namespace names, with the immediate parent first.
  205. llvm::SmallVector<SemIR::NameScopeId> new_namespaces;
  206. while (import_parent_scope_id != SemIR::NameScopeId::Package) {
  207. // If the namespace was already copied, reuse the results.
  208. if (auto result = copied_namespaces.Lookup(import_parent_scope_id)) {
  209. // We inject names at the provided scope, and don't need to keep
  210. // traversing parents.
  211. scope_cursor = result.value();
  212. break;
  213. }
  214. // The namespace hasn't been copied yet, so add it to our list.
  215. const auto& scope = import_sem_ir.name_scopes().Get(import_parent_scope_id);
  216. auto scope_inst =
  217. import_sem_ir.insts().GetAs<SemIR::Namespace>(scope.inst_id());
  218. new_namespaces.push_back(scope_inst.name_scope_id);
  219. import_parent_scope_id = scope.parent_scope_id();
  220. }
  221. // Add ancestor namespace names, starting with the outermost.
  222. for (auto import_scope_id : llvm::reverse(new_namespaces)) {
  223. auto import_scope = import_sem_ir.name_scopes().Get(import_scope_id);
  224. auto name_id =
  225. CopyNameFromImportIR(context, import_sem_ir, import_scope.name_id());
  226. scope_cursor =
  227. CopySingleNameScopeFromImportIR(
  228. context, namespace_type_id, &copied_namespaces, ir_id,
  229. import_scope.inst_id(), import_scope_id, scope_cursor, name_id)
  230. .name_scope_id;
  231. }
  232. return scope_cursor;
  233. }
  234. // Adds an ImportRef for an entity, handling merging if needed.
  235. static auto AddImportRefOrMerge(Context& context, SemIR::ImportIRId ir_id,
  236. const SemIR::File& import_sem_ir,
  237. SemIR::InstId import_inst_id,
  238. SemIR::NameScopeId parent_scope_id,
  239. SemIR::NameId name_id) -> void {
  240. // Leave a placeholder that the inst comes from the other IR.
  241. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  242. auto [inserted, entry_id] = parent_scope.LookupOrAdd(
  243. name_id,
  244. // This InstId is temporary and would be overridden if used.
  245. SemIR::InstId::None, SemIR::AccessKind::Public);
  246. auto& entry = parent_scope.GetEntry(entry_id);
  247. if (inserted) {
  248. auto entity_name_id = context.entity_names().Add(
  249. {.name_id = name_id, .parent_scope_id = parent_scope_id});
  250. entry.result = SemIR::ScopeLookupResult::MakeFound(
  251. AddImportRef(context, {.ir_id = ir_id, .inst_id = import_inst_id},
  252. entity_name_id),
  253. SemIR::AccessKind::Public);
  254. return;
  255. }
  256. auto inst_id = entry.result.target_inst_id();
  257. auto prev_ir_inst = GetCanonicalImportIRInst(context, inst_id);
  258. VerifySameCanonicalImportIRInst(context, inst_id, prev_ir_inst, ir_id,
  259. &import_sem_ir, import_inst_id);
  260. }
  261. namespace {
  262. // A scope in the API file that still needs to be copied to the implementation
  263. // file. Only used for API file imports.
  264. struct TodoScope {
  265. // The scope's instruction in the API file.
  266. SemIR::InstId api_inst_id;
  267. // The scope in the API file.
  268. SemIR::NameScopeId api_scope_id;
  269. // The already-translated scope name in the implementation file.
  270. SemIR::NameId impl_name_id;
  271. // The already-copied parent scope in the implementation file.
  272. SemIR::NameScopeId impl_parent_scope_id;
  273. };
  274. } // namespace
  275. // Adds an ImportRef to a name scope.
  276. static auto AddScopedImportRef(Context& context,
  277. SemIR::NameScopeId parent_scope_id,
  278. SemIR::NameScope& parent_scope,
  279. SemIR::NameId name_id,
  280. SemIR::ImportIRInst import_inst,
  281. SemIR::AccessKind access_kind) -> SemIR::InstId {
  282. // Add an ImportRef for other instructions.
  283. auto impl_entity_name_id = context.entity_names().Add(
  284. {.name_id = name_id, .parent_scope_id = parent_scope_id});
  285. auto import_ref_id = AddImportRef(context, import_inst, impl_entity_name_id);
  286. parent_scope.AddRequired({.name_id = name_id,
  287. .result = SemIR::ScopeLookupResult::MakeFound(
  288. import_ref_id, access_kind)});
  289. return import_ref_id;
  290. }
  291. // Imports entries in a specific scope into the current file.
  292. static auto ImportScopeFromApiFile(Context& context,
  293. const SemIR::File& api_sem_ir,
  294. SemIR::NameScopeId api_scope_id,
  295. SemIR::NameScopeId impl_scope_id,
  296. llvm::SmallVector<TodoScope>& todo_scopes)
  297. -> void {
  298. const auto& api_scope = api_sem_ir.name_scopes().Get(api_scope_id);
  299. auto& impl_scope = context.name_scopes().Get(impl_scope_id);
  300. for (const auto& api_entry : api_scope.entries()) {
  301. if (api_entry.result.is_poisoned()) {
  302. continue;
  303. }
  304. auto impl_name_id =
  305. CopyNameFromImportIR(context, api_sem_ir, api_entry.name_id);
  306. if (auto ns = api_sem_ir.insts().TryGetAs<SemIR::Namespace>(
  307. api_entry.result.target_inst_id())) {
  308. // Ignore cross-package imports. These will be handled through
  309. // ImportLibrariesFromOtherPackage.
  310. if (api_scope_id == SemIR::NameScopeId::Package) {
  311. const auto& ns_scope = api_sem_ir.name_scopes().Get(ns->name_scope_id);
  312. if (!ns_scope.import_ir_scopes().empty()) {
  313. continue;
  314. }
  315. }
  316. // Namespaces will be recursed into. Name scope creation is delayed in
  317. // order to avoid invalidating api_scope/impl_scope.
  318. todo_scopes.push_back({.api_inst_id = api_entry.result.target_inst_id(),
  319. .api_scope_id = ns->name_scope_id,
  320. .impl_name_id = impl_name_id,
  321. .impl_parent_scope_id = impl_scope_id});
  322. } else {
  323. // Add an ImportRef for other instructions.
  324. AddScopedImportRef(context, impl_scope_id, impl_scope, impl_name_id,
  325. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  326. .inst_id = api_entry.result.target_inst_id()},
  327. api_entry.result.access_kind());
  328. }
  329. }
  330. }
  331. auto ImportApiFile(Context& context, SemIR::TypeId namespace_type_id,
  332. const SemIR::File& api_sem_ir) -> void {
  333. context.import_ir_constant_values()[SemIR::ImportIRId::ApiForImpl.index].Set(
  334. SemIR::Namespace::PackageInstId,
  335. context.constant_values().Get(SemIR::Namespace::PackageInstId));
  336. llvm::SmallVector<TodoScope> todo_scopes = {};
  337. ImportScopeFromApiFile(context, api_sem_ir, SemIR::NameScopeId::Package,
  338. SemIR::NameScopeId::Package, todo_scopes);
  339. while (!todo_scopes.empty()) {
  340. auto todo_scope = todo_scopes.pop_back_val();
  341. auto impl_scope_id =
  342. CopySingleNameScopeFromImportIR(
  343. context, namespace_type_id, /*copied_namespaces=*/nullptr,
  344. SemIR::ImportIRId::ApiForImpl, todo_scope.api_inst_id,
  345. todo_scope.api_scope_id, todo_scope.impl_parent_scope_id,
  346. todo_scope.impl_name_id)
  347. .name_scope_id;
  348. ImportScopeFromApiFile(context, api_sem_ir, todo_scope.api_scope_id,
  349. impl_scope_id, todo_scopes);
  350. }
  351. }
  352. auto ImportLibrariesFromCurrentPackage(
  353. Context& context, SemIR::TypeId namespace_type_id,
  354. llvm::ArrayRef<SemIR::ImportIR> import_irs) -> void {
  355. for (auto import_ir : import_irs) {
  356. auto ir_id = AddImportIR(context, import_ir);
  357. context.import_ir_constant_values()[ir_id.index].Set(
  358. SemIR::Namespace::PackageInstId,
  359. context.constant_values().Get(SemIR::Namespace::PackageInstId));
  360. for (const auto import_inst_id :
  361. import_ir.sem_ir->inst_blocks().Get(SemIR::InstBlockId::Exports)) {
  362. auto import_inst = import_ir.sem_ir->insts().Get(import_inst_id);
  363. auto [import_name_id, import_parent_scope_id] =
  364. GetImportName(*import_ir.sem_ir, import_inst);
  365. Map<SemIR::NameScopeId, SemIR::NameScopeId> copied_namespaces;
  366. auto name_id =
  367. CopyNameFromImportIR(context, *import_ir.sem_ir, import_name_id);
  368. SemIR::NameScopeId parent_scope_id = CopyAncestorNameScopesFromImportIR(
  369. context, namespace_type_id, *import_ir.sem_ir, ir_id,
  370. import_parent_scope_id, copied_namespaces);
  371. if (auto import_namespace_inst = import_inst.TryAs<SemIR::Namespace>()) {
  372. // Namespaces are always imported because they're essential for
  373. // qualifiers, and the type is simple.
  374. CopySingleNameScopeFromImportIR(
  375. context, namespace_type_id, &copied_namespaces, ir_id,
  376. import_inst_id, import_namespace_inst->name_scope_id,
  377. parent_scope_id, name_id);
  378. } else {
  379. AddImportRefOrMerge(context, ir_id, *import_ir.sem_ir, import_inst_id,
  380. parent_scope_id, name_id);
  381. }
  382. }
  383. // If an import of the current package caused an error for the imported
  384. // file, it transitively affects the current file too.
  385. if (import_ir.sem_ir->name_scopes()
  386. .Get(SemIR::NameScopeId::Package)
  387. .has_error()) {
  388. context.name_scopes().Get(SemIR::NameScopeId::Package).set_has_error();
  389. }
  390. }
  391. }
  392. auto ImportLibrariesFromOtherPackage(Context& context,
  393. SemIR::TypeId namespace_type_id,
  394. SemIR::InstId import_decl_id,
  395. PackageNameId package_id,
  396. llvm::ArrayRef<SemIR::ImportIR> import_irs,
  397. bool has_load_error) -> void {
  398. CARBON_CHECK(has_load_error || !import_irs.empty(),
  399. "There should be either a load error or at least one IR.");
  400. auto name_id = SemIR::NameId::ForPackageName(package_id);
  401. AddImportNamespaceResult result = AddImportNamespace(
  402. context, namespace_type_id, name_id, SemIR::NameScopeId::Package,
  403. /*diagnose_duplicate_namespace=*/true, [&] { return import_decl_id; });
  404. auto namespace_const_id = context.constant_values().Get(result.inst_id);
  405. auto& scope = context.name_scopes().Get(result.name_scope_id);
  406. scope.set_is_closed_import(
  407. !result.is_duplicate_of_namespace_in_current_package);
  408. for (auto import_ir : import_irs) {
  409. auto ir_id = AddImportIR(context, import_ir);
  410. scope.AddImportIRScope({ir_id, SemIR::NameScopeId::Package});
  411. context.import_ir_constant_values()[ir_id.index].Set(
  412. SemIR::Namespace::PackageInstId, namespace_const_id);
  413. }
  414. if (has_load_error) {
  415. scope.set_has_error();
  416. }
  417. }
  418. // Looks up a name in a scope imported from another package. An `identifier` is
  419. // provided if `name_id` corresponds to an identifier in the current file;
  420. // otherwise, `name_id` is file-agnostic and can be used directly.
  421. static auto LookupNameInImport(const SemIR::File& import_ir,
  422. SemIR::NameScopeId import_scope_id,
  423. SemIR::NameId name_id,
  424. llvm::StringRef identifier)
  425. -> const Carbon::SemIR::NameScope::Entry* {
  426. // Determine the NameId in the import IR.
  427. SemIR::NameId import_name_id = name_id;
  428. if (!identifier.empty()) {
  429. auto import_identifier_id = import_ir.identifiers().Lookup(identifier);
  430. if (!import_identifier_id.has_value()) {
  431. // Name doesn't exist in the import IR.
  432. return nullptr;
  433. }
  434. import_name_id = SemIR::NameId::ForIdentifier(import_identifier_id);
  435. }
  436. // Look up the name in the import scope.
  437. const auto& import_scope = import_ir.name_scopes().Get(import_scope_id);
  438. auto import_scope_entry_id = import_scope.Lookup(import_name_id);
  439. if (!import_scope_entry_id) {
  440. // Name doesn't exist in the import scope.
  441. return nullptr;
  442. }
  443. const auto& import_scope_entry =
  444. import_scope.GetEntry(*import_scope_entry_id);
  445. if (import_scope_entry.result.access_kind() != SemIR::AccessKind::Public) {
  446. // Ignore cross-package non-public names.
  447. return nullptr;
  448. }
  449. return &import_scope_entry;
  450. }
  451. // Adds a namespace that points to one in another package.
  452. static auto AddNamespaceFromOtherPackage(Context& context,
  453. SemIR::ImportIRId import_ir_id,
  454. SemIR::InstId import_inst_id,
  455. SemIR::Namespace import_ns,
  456. SemIR::NameScopeId parent_scope_id,
  457. SemIR::NameId name_id)
  458. -> SemIR::InstId {
  459. auto namespace_type_id =
  460. GetSingletonType(context, SemIR::NamespaceType::SingletonInstId);
  461. AddImportNamespaceResult result = CopySingleNameScopeFromImportIR(
  462. context, namespace_type_id, /*copied_namespaces=*/nullptr, import_ir_id,
  463. import_inst_id, import_ns.name_scope_id, parent_scope_id, name_id);
  464. auto& scope = context.name_scopes().Get(result.name_scope_id);
  465. scope.set_is_closed_import(
  466. !result.is_duplicate_of_namespace_in_current_package);
  467. scope.AddImportIRScope({import_ir_id, import_ns.name_scope_id});
  468. return result.inst_id;
  469. }
  470. auto ImportNameFromOtherPackage(
  471. Context& context, SemIRLoc loc, SemIR::NameScopeId scope_id,
  472. llvm::ArrayRef<std::pair<SemIR::ImportIRId, SemIR::NameScopeId>>
  473. import_ir_scopes,
  474. SemIR::NameId name_id) -> SemIR::InstId {
  475. // If the name is an identifier, get the string first so that it can be shared
  476. // when there are multiple IRs.
  477. llvm::StringRef identifier;
  478. if (auto identifier_id = name_id.AsIdentifierId();
  479. identifier_id.has_value()) {
  480. identifier = context.identifiers().Get(identifier_id);
  481. CARBON_CHECK(!identifier.empty());
  482. }
  483. // Annotate diagnostics as occurring during this name lookup.
  484. DiagnosticAnnotationScope annotate_diagnostics(
  485. &context.emitter(), [&](auto& builder) {
  486. CARBON_DIAGNOSTIC(InNameLookup, Note, "in name lookup for `{0}`",
  487. SemIR::NameId);
  488. builder.Note(loc, InNameLookup, name_id);
  489. });
  490. // Although we track the result here and look in each IR, we pretty much use
  491. // the first result.
  492. auto result_id = SemIR::InstId::None;
  493. // The canonical IR and inst_id for where `result_id` came from, which may be
  494. // indirectly imported. This is only resolved on a conflict, when it can be
  495. // used to determine the conflict is actually the same instruction.
  496. std::optional<SemIR::ImportIRInst> canonical_result_inst;
  497. for (auto [import_ir_id, import_scope_id] : import_ir_scopes) {
  498. auto& import_ir = context.import_irs().Get(import_ir_id);
  499. const auto* import_scope_entry = LookupNameInImport(
  500. *import_ir.sem_ir, import_scope_id, name_id, identifier);
  501. if (!import_scope_entry) {
  502. continue;
  503. }
  504. SemIR::InstId import_scope_inst_id =
  505. import_scope_entry->result.target_inst_id();
  506. auto import_inst = import_ir.sem_ir->insts().Get(import_scope_inst_id);
  507. if (import_inst.Is<SemIR::AnyImportRef>()) {
  508. // This entity was added to name lookup by using an import, and is not
  509. // exported.
  510. continue;
  511. }
  512. // Add the first result found.
  513. if (!result_id.has_value()) {
  514. // If the imported instruction is a namespace, we add it directly instead
  515. // of as an ImportRef.
  516. if (auto import_ns = import_inst.TryAs<SemIR::Namespace>()) {
  517. result_id = AddNamespaceFromOtherPackage(context, import_ir_id,
  518. import_scope_inst_id,
  519. *import_ns, scope_id, name_id);
  520. } else {
  521. result_id = AddScopedImportRef(
  522. context, scope_id, context.name_scopes().Get(scope_id), name_id,
  523. {.ir_id = import_ir_id, .inst_id = import_scope_inst_id},
  524. SemIR::AccessKind::Public);
  525. LoadImportRef(context, result_id);
  526. }
  527. continue;
  528. }
  529. // When namespaces collide between files, merge lookup in the scopes.
  530. if (auto import_ns = import_inst.TryAs<SemIR::Namespace>()) {
  531. if (auto ns = context.insts().TryGetAs<SemIR::Namespace>(result_id)) {
  532. auto& name_scope = context.name_scopes().Get(ns->name_scope_id);
  533. name_scope.AddImportIRScope({import_ir_id, import_ns->name_scope_id});
  534. continue;
  535. }
  536. }
  537. // When there's a name collision, they need to either be the same canonical
  538. // instruction, or we'll diagnose.
  539. if (!canonical_result_inst) {
  540. canonical_result_inst = GetCanonicalImportIRInst(context, result_id);
  541. }
  542. VerifySameCanonicalImportIRInst(context, result_id, *canonical_result_inst,
  543. import_ir_id, import_ir.sem_ir,
  544. import_scope_inst_id);
  545. }
  546. return result_id;
  547. }
  548. } // namespace Carbon::Check