import.cpp 32 KB

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