import.cpp 26 KB

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