import.cpp 13 KB

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