import.cpp 26 KB

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