import.cpp 29 KB

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