import.cpp 25 KB

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