import.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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/merge.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/name_scope.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Returns name information for the entity, corresponding to IDs in the import
  20. // IR rather than the current IR.
  21. static auto GetImportName(const SemIR::File& import_sem_ir,
  22. SemIR::Inst import_inst)
  23. -> std::pair<SemIR::NameId, SemIR::NameScopeId> {
  24. CARBON_KIND_SWITCH(import_inst) {
  25. case SemIR::BindAlias::Kind:
  26. case SemIR::BindName::Kind:
  27. case SemIR::BindSymbolicName::Kind:
  28. case SemIR::ExportDecl::Kind: {
  29. auto bind_inst = import_inst.As<SemIR::AnyBindNameOrExportDecl>();
  30. const auto& bind_name =
  31. import_sem_ir.bind_names().Get(bind_inst.bind_name_id);
  32. return {bind_name.name_id, bind_name.parent_scope_id};
  33. }
  34. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  35. const auto& class_info = import_sem_ir.classes().Get(class_decl.class_id);
  36. return {class_info.name_id, class_info.parent_scope_id};
  37. }
  38. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  39. const auto& function =
  40. import_sem_ir.functions().Get(function_decl.function_id);
  41. return {function.name_id, function.parent_scope_id};
  42. }
  43. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  44. const auto& interface =
  45. import_sem_ir.interfaces().Get(interface_decl.interface_id);
  46. return {interface.name_id, interface.parent_scope_id};
  47. }
  48. case CARBON_KIND(SemIR::Namespace ns): {
  49. const auto& scope = import_sem_ir.name_scopes().Get(ns.name_scope_id);
  50. return {scope.name_id, scope.parent_scope_id};
  51. }
  52. default:
  53. CARBON_FATAL() << "Unsupported export kind: " << import_inst;
  54. }
  55. }
  56. // Translate the name to the current IR. It will usually be an identifier, but
  57. // could also be a builtin name ID which is equivalent cross-IR.
  58. static auto CopyNameFromImportIR(Context& context,
  59. const SemIR::File& import_sem_ir,
  60. SemIR::NameId import_name_id) {
  61. if (auto import_identifier_id = import_name_id.AsIdentifierId();
  62. import_identifier_id.is_valid()) {
  63. auto name = import_sem_ir.identifiers().Get(import_identifier_id);
  64. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  65. }
  66. return import_name_id;
  67. }
  68. // Adds a namespace to the IR. The bool on return is true if there was a name
  69. // conflict. diagnose_duplicate_namespace is used when handling a cross-package
  70. // import, where an existing namespace is in the current package and the new
  71. // namespace is a different package.
  72. static auto AddNamespace(
  73. Context& context, SemIR::TypeId namespace_type_id,
  74. Parse::ImportDeclId node_id, SemIR::NameId name_id,
  75. SemIR::NameScopeId parent_scope_id, bool diagnose_duplicate_namespace,
  76. std::optional<llvm::function_ref<SemIR::InstId()>> make_import_id)
  77. -> std::tuple<SemIR::NameScopeId, SemIR::ConstantId, bool> {
  78. auto* parent_scope = &context.name_scopes().Get(parent_scope_id);
  79. auto insert_result =
  80. parent_scope->name_map.Insert(name_id, parent_scope->names.size());
  81. if (!insert_result.is_inserted()) {
  82. auto inst_id = parent_scope->names[insert_result.value()].inst_id;
  83. if (auto namespace_inst =
  84. context.insts().TryGetAs<SemIR::Namespace>(inst_id)) {
  85. if (diagnose_duplicate_namespace) {
  86. context.DiagnoseDuplicateName(node_id, inst_id);
  87. }
  88. return {namespace_inst->name_scope_id,
  89. context.constant_values().Get(inst_id), true};
  90. }
  91. }
  92. auto import_id =
  93. make_import_id ? (*make_import_id)() : SemIR::InstId::Invalid;
  94. auto namespace_inst = SemIR::Namespace{
  95. namespace_type_id, SemIR::NameScopeId::Invalid, import_id};
  96. // Use the invalid node because there's no node to associate with.
  97. auto namespace_id =
  98. context.AddPlaceholderInst(SemIR::LocIdAndInst(node_id, namespace_inst));
  99. namespace_inst.name_scope_id =
  100. context.name_scopes().Add(namespace_id, name_id, parent_scope_id);
  101. context.ReplaceInstBeforeConstantUse(namespace_id, namespace_inst);
  102. // Note we have to get the parent scope freshly, creating the imported
  103. // namespace may invalidate the pointer above.
  104. parent_scope = &context.name_scopes().Get(parent_scope_id);
  105. // Diagnose if there's a name conflict, but still produce the namespace to
  106. // supersede the name conflict in order to avoid repeat diagnostics.
  107. if (!insert_result.is_inserted()) {
  108. auto& entry = parent_scope->names[insert_result.value()];
  109. context.DiagnoseDuplicateName(namespace_id, entry.inst_id);
  110. entry.inst_id = namespace_id;
  111. entry.access_kind = SemIR::AccessKind::Public;
  112. } else {
  113. parent_scope->names.push_back({.name_id = name_id,
  114. .inst_id = namespace_id,
  115. .access_kind = SemIR::AccessKind::Public});
  116. }
  117. return {namespace_inst.name_scope_id,
  118. context.constant_values().Get(namespace_id), false};
  119. }
  120. // Adds a copied namespace to the cache.
  121. static auto CacheCopiedNamespace(
  122. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces,
  123. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId to_scope_id)
  124. -> void {
  125. auto result = copied_namespaces.Insert(import_scope_id, to_scope_id);
  126. CARBON_CHECK(result.is_inserted() || result.value() == to_scope_id)
  127. << "Copy result for namespace changed from " << import_scope_id << " to "
  128. << to_scope_id;
  129. }
  130. // Copies a namespace from the import IR, returning its ID. This may diagnose
  131. // name conflicts, but that won't change the result because namespaces supersede
  132. // other names in conflicts. copied_namespaces is optional.
  133. static auto CopySingleNameScopeFromImportIR(
  134. Context& context, SemIR::TypeId namespace_type_id,
  135. Map<SemIR::NameScopeId, SemIR::NameScopeId>* copied_namespaces,
  136. SemIR::ImportIRId ir_id, SemIR::InstId import_inst_id,
  137. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId parent_scope_id,
  138. SemIR::NameId name_id) -> SemIR::NameScopeId {
  139. // Produce the namespace for the entry.
  140. auto make_import_id = [&]() {
  141. auto bind_name_id = context.bind_names().Add(
  142. {.name_id = name_id,
  143. .parent_scope_id = parent_scope_id,
  144. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  145. auto import_ir_inst_id = context.import_ir_insts().Add(
  146. {.ir_id = ir_id, .inst_id = import_inst_id});
  147. return context.AddInst<SemIR::ImportRefLoaded>(
  148. import_ir_inst_id, {.type_id = namespace_type_id,
  149. .import_ir_inst_id = import_ir_inst_id,
  150. .bind_name_id = bind_name_id});
  151. };
  152. auto [namespace_scope_id, namespace_const_id, _] = AddNamespace(
  153. context, namespace_type_id, Parse::NodeId::Invalid, name_id,
  154. parent_scope_id, /*diagnose_duplicate_namespace=*/false, make_import_id);
  155. context.import_ir_constant_values()[ir_id.index].Set(import_inst_id,
  156. namespace_const_id);
  157. if (copied_namespaces) {
  158. CacheCopiedNamespace(*copied_namespaces, import_scope_id,
  159. namespace_scope_id);
  160. }
  161. return namespace_scope_id;
  162. }
  163. // Copies ancestor name scopes from the import IR. Handles the parent traversal.
  164. // Returns the NameScope corresponding to the copied import_parent_scope_id.
  165. static auto CopyAncestorNameScopesFromImportIR(
  166. Context& context, SemIR::TypeId namespace_type_id,
  167. const SemIR::File& import_sem_ir, SemIR::ImportIRId ir_id,
  168. SemIR::NameScopeId import_parent_scope_id,
  169. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces)
  170. -> SemIR::NameScopeId {
  171. // Package-level names don't need work.
  172. if (import_parent_scope_id == SemIR::NameScopeId::Package) {
  173. return import_parent_scope_id;
  174. }
  175. // The scope to add namespaces to. Note this may change while looking at
  176. // parent scopes, if we encounter a namespace that's already added.
  177. auto scope_cursor = SemIR::NameScopeId::Package;
  178. // Build a stack of ancestor namespace names, with the immediate parent first.
  179. llvm::SmallVector<SemIR::NameScopeId> new_namespaces;
  180. while (import_parent_scope_id != SemIR::NameScopeId::Package) {
  181. // If the namespace was already copied, reuse the results.
  182. if (auto result = copied_namespaces.Lookup(import_parent_scope_id)) {
  183. // We inject names at the provided scope, and don't need to keep
  184. // traversing parents.
  185. scope_cursor = result.value();
  186. break;
  187. }
  188. // The namespace hasn't been copied yet, so add it to our list.
  189. const auto& scope = import_sem_ir.name_scopes().Get(import_parent_scope_id);
  190. auto scope_inst =
  191. import_sem_ir.insts().GetAs<SemIR::Namespace>(scope.inst_id);
  192. new_namespaces.push_back(scope_inst.name_scope_id);
  193. import_parent_scope_id = scope.parent_scope_id;
  194. }
  195. // Add ancestor namespace names, starting with the outermost.
  196. for (auto import_scope_id : llvm::reverse(new_namespaces)) {
  197. auto import_scope = import_sem_ir.name_scopes().Get(import_scope_id);
  198. auto name_id =
  199. CopyNameFromImportIR(context, import_sem_ir, import_scope.name_id);
  200. scope_cursor = CopySingleNameScopeFromImportIR(
  201. context, namespace_type_id, &copied_namespaces, ir_id,
  202. import_scope.inst_id, import_scope_id, scope_cursor, name_id);
  203. }
  204. return scope_cursor;
  205. }
  206. // Adds an ImportRef for an entity, handling merging if needed.
  207. static auto AddImportRefOrMerge(Context& context, SemIR::ImportIRId ir_id,
  208. const SemIR::File& import_sem_ir,
  209. SemIR::InstId import_inst_id,
  210. SemIR::NameScopeId parent_scope_id,
  211. SemIR::NameId name_id) -> void {
  212. // Leave a placeholder that the inst comes from the other IR.
  213. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  214. auto insert = parent_scope.name_map.Insert(name_id, [&] {
  215. auto bind_name_id = context.bind_names().Add(
  216. {.name_id = name_id,
  217. .parent_scope_id = parent_scope_id,
  218. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  219. int index = parent_scope.names.size();
  220. parent_scope.names.push_back(
  221. {.name_id = name_id,
  222. .inst_id =
  223. AddImportRef(context, {.ir_id = ir_id, .inst_id = import_inst_id},
  224. bind_name_id),
  225. .access_kind = SemIR::AccessKind::Public});
  226. return index;
  227. });
  228. if (insert.is_inserted()) {
  229. return;
  230. }
  231. auto inst_id = parent_scope.names[insert.value()].inst_id;
  232. auto prev_ir_inst =
  233. GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  234. VerifySameCanonicalImportIRInst(context, inst_id, prev_ir_inst, ir_id,
  235. &import_sem_ir, import_inst_id);
  236. }
  237. namespace {
  238. // A scope in the API file that still needs to be copied to the implementation
  239. // file. Only used for API file imports.
  240. struct TodoScope {
  241. // The scope's instruction in the API file.
  242. SemIR::InstId api_inst_id;
  243. // The scope in the API file.
  244. SemIR::NameScopeId api_scope_id;
  245. // The already-translated scope name in the implementation file.
  246. SemIR::NameId impl_name_id;
  247. // The already-copied parent scope in the implementation file.
  248. SemIR::NameScopeId impl_parent_scope_id;
  249. };
  250. } // namespace
  251. // Imports entries in a specific scope into the current file.
  252. static auto ImportScopeFromApiFile(Context& context,
  253. const SemIR::File& api_sem_ir,
  254. SemIR::NameScopeId api_scope_id,
  255. SemIR::NameScopeId impl_scope_id,
  256. llvm::SmallVector<TodoScope>& todo_scopes)
  257. -> void {
  258. const auto& api_scope = api_sem_ir.name_scopes().Get(api_scope_id);
  259. auto& impl_scope = context.name_scopes().Get(impl_scope_id);
  260. for (const auto& api_entry : api_scope.names) {
  261. auto impl_name_id =
  262. CopyNameFromImportIR(context, api_sem_ir, api_entry.name_id);
  263. if (auto ns =
  264. api_sem_ir.insts().TryGetAs<SemIR::Namespace>(api_entry.inst_id)) {
  265. // Ignore cross-package imports. These will be handled through
  266. // ImportLibrariesFromOtherPackage.
  267. if (api_scope_id == SemIR::NameScopeId::Package) {
  268. const auto& ns_scope = api_sem_ir.name_scopes().Get(ns->name_scope_id);
  269. if (!ns_scope.import_ir_scopes.empty()) {
  270. continue;
  271. }
  272. }
  273. // Namespaces will be recursed into. Name scope creation is delayed in
  274. // order to avoid invalidating api_scope/impl_scope.
  275. todo_scopes.push_back({.api_inst_id = api_entry.inst_id,
  276. .api_scope_id = ns->name_scope_id,
  277. .impl_name_id = impl_name_id,
  278. .impl_parent_scope_id = impl_scope_id});
  279. } else {
  280. // Add an ImportRef for other instructions.
  281. auto impl_bind_name_id = context.bind_names().Add(
  282. {.name_id = impl_name_id,
  283. .parent_scope_id = impl_scope_id,
  284. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  285. auto import_ref_id = AddImportRef(context,
  286. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  287. .inst_id = api_entry.inst_id},
  288. impl_bind_name_id);
  289. impl_scope.AddRequired({.name_id = impl_name_id,
  290. .inst_id = import_ref_id,
  291. .access_kind = api_entry.access_kind});
  292. }
  293. }
  294. }
  295. auto ImportApiFile(Context& context, SemIR::TypeId namespace_type_id,
  296. Parse::ImportDeclId node_id, const SemIR::File& api_sem_ir)
  297. -> void {
  298. SetApiImportIR(context, {.node_id = node_id, .sem_ir = &api_sem_ir});
  299. context.import_ir_constant_values()[SemIR::ImportIRId::ApiForImpl.index].Set(
  300. SemIR::InstId::PackageNamespace,
  301. context.constant_values().Get(SemIR::InstId::PackageNamespace));
  302. llvm::SmallVector<TodoScope> todo_scopes = {};
  303. ImportScopeFromApiFile(context, api_sem_ir, SemIR::NameScopeId::Package,
  304. SemIR::NameScopeId::Package, todo_scopes);
  305. while (!todo_scopes.empty()) {
  306. auto todo_scope = todo_scopes.pop_back_val();
  307. auto impl_scope_id = CopySingleNameScopeFromImportIR(
  308. context, namespace_type_id, /*copied_namespaces=*/nullptr,
  309. SemIR::ImportIRId::ApiForImpl, todo_scope.api_inst_id,
  310. todo_scope.api_scope_id, todo_scope.impl_parent_scope_id,
  311. todo_scope.impl_name_id);
  312. ImportScopeFromApiFile(context, api_sem_ir, todo_scope.api_scope_id,
  313. impl_scope_id, todo_scopes);
  314. }
  315. }
  316. auto ImportLibrariesFromCurrentPackage(
  317. Context& context, SemIR::TypeId namespace_type_id,
  318. llvm::ArrayRef<SemIR::ImportIR> import_irs) -> void {
  319. for (auto import_ir : import_irs) {
  320. auto ir_id = AddImportIR(context, import_ir);
  321. context.import_ir_constant_values()[ir_id.index].Set(
  322. SemIR::InstId::PackageNamespace,
  323. context.constant_values().Get(SemIR::InstId::PackageNamespace));
  324. for (const auto import_inst_id :
  325. import_ir.sem_ir->inst_blocks().Get(SemIR::InstBlockId::Exports)) {
  326. auto import_inst = import_ir.sem_ir->insts().Get(import_inst_id);
  327. auto [import_name_id, import_parent_scope_id] =
  328. GetImportName(*import_ir.sem_ir, import_inst);
  329. Map<SemIR::NameScopeId, SemIR::NameScopeId> copied_namespaces;
  330. auto name_id =
  331. CopyNameFromImportIR(context, *import_ir.sem_ir, import_name_id);
  332. SemIR::NameScopeId parent_scope_id = CopyAncestorNameScopesFromImportIR(
  333. context, namespace_type_id, *import_ir.sem_ir, ir_id,
  334. import_parent_scope_id, copied_namespaces);
  335. if (auto import_namespace_inst = import_inst.TryAs<SemIR::Namespace>()) {
  336. // Namespaces are always imported because they're essential for
  337. // qualifiers, and the type is simple.
  338. CopySingleNameScopeFromImportIR(
  339. context, namespace_type_id, &copied_namespaces, ir_id,
  340. import_inst_id, import_namespace_inst->name_scope_id,
  341. parent_scope_id, name_id);
  342. } else {
  343. AddImportRefOrMerge(context, ir_id, *import_ir.sem_ir, import_inst_id,
  344. parent_scope_id, name_id);
  345. }
  346. }
  347. // If an import of the current package caused an error for the imported
  348. // file, it transitively affects the current file too.
  349. if (import_ir.sem_ir->name_scopes()
  350. .Get(SemIR::NameScopeId::Package)
  351. .has_error) {
  352. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error = true;
  353. }
  354. }
  355. }
  356. auto ImportLibrariesFromOtherPackage(Context& context,
  357. SemIR::TypeId namespace_type_id,
  358. Parse::ImportDeclId node_id,
  359. IdentifierId package_id,
  360. llvm::ArrayRef<SemIR::ImportIR> import_irs,
  361. bool has_load_error) -> void {
  362. CARBON_CHECK(has_load_error || !import_irs.empty())
  363. << "There should be either a load error or at least one IR.";
  364. auto name_id = SemIR::NameId::ForIdentifier(package_id);
  365. auto [namespace_scope_id, namespace_const_id, is_duplicate] = AddNamespace(
  366. context, namespace_type_id, node_id, name_id, SemIR::NameScopeId::Package,
  367. /*diagnose_duplicate_namespace=*/true, /*make_import_id=*/std::nullopt);
  368. auto& scope = context.name_scopes().Get(namespace_scope_id);
  369. scope.is_closed_import = !is_duplicate;
  370. for (auto import_ir : import_irs) {
  371. auto ir_id = AddImportIR(context, import_ir);
  372. scope.import_ir_scopes.push_back({ir_id, SemIR::NameScopeId::Package});
  373. context.import_ir_constant_values()[ir_id.index].Set(
  374. SemIR::InstId::PackageNamespace, namespace_const_id);
  375. }
  376. if (has_load_error) {
  377. scope.has_error = has_load_error;
  378. }
  379. }
  380. } // namespace Carbon::Check