import.cpp 14 KB

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