import.cpp 26 KB

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