import.cpp 30 KB

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