import.cpp 28 KB

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