import.cpp 30 KB

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