import.cpp 26 KB

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