import.cpp 25 KB

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