import.cpp 26 KB

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