import.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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::ExternDecl extern_decl): {
  34. return GetImportName(import_sem_ir,
  35. import_sem_ir.insts().Get(extern_decl.decl_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.enclosing_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.enclosing_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.enclosing_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::ImportDirectiveId node_id, SemIR::NameId name_id,
  74. SemIR::NameScopeId enclosing_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& enclosing_scope = context.name_scopes().Get(enclosing_scope_id);
  78. auto [it, success] =
  79. enclosing_scope.names.insert({name_id, SemIR::InstId::Invalid});
  80. if (!success) {
  81. if (auto namespace_inst =
  82. context.insts().TryGetAs<SemIR::Namespace>(it->second)) {
  83. if (diagnose_duplicate_namespace) {
  84. context.DiagnoseDuplicateName(node_id, it->second);
  85. }
  86. return {namespace_inst->name_scope_id,
  87. context.constant_values().Get(it->second), true};
  88. }
  89. }
  90. auto import_id =
  91. make_import_id ? (*make_import_id)() : SemIR::InstId::Invalid;
  92. auto namespace_inst = SemIR::Namespace{
  93. namespace_type_id, SemIR::NameScopeId::Invalid, import_id};
  94. // Use the invalid node because there's no node to associate with.
  95. auto namespace_id = context.AddPlaceholderInst({node_id, namespace_inst});
  96. namespace_inst.name_scope_id =
  97. context.name_scopes().Add(namespace_id, name_id, enclosing_scope_id);
  98. context.ReplaceInstBeforeConstantUse(namespace_id, namespace_inst);
  99. // Diagnose if there's a name conflict, but still produce the namespace to
  100. // supersede the name conflict in order to avoid repeat diagnostics.
  101. if (!success) {
  102. context.DiagnoseDuplicateName(namespace_id, it->second);
  103. }
  104. it->second = namespace_id;
  105. return {namespace_inst.name_scope_id,
  106. context.constant_values().Get(namespace_id), false};
  107. }
  108. // Adds a copied namespace to the cache.
  109. static auto CacheCopiedNamespace(
  110. llvm::DenseMap<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces,
  111. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId to_scope_id)
  112. -> void {
  113. auto [it, success] = copied_namespaces.insert({import_scope_id, to_scope_id});
  114. CARBON_CHECK(success || it->second == to_scope_id)
  115. << "Copy result for namespace changed from " << import_scope_id << " to "
  116. << to_scope_id;
  117. }
  118. // Copies a namespace from the import IR, returning its ID. This may diagnose
  119. // name conflicts, but that won't change the result because namespaces supersede
  120. // other names in conflicts.
  121. static auto CopySingleNameScopeFromImportIR(
  122. Context& context, SemIR::TypeId namespace_type_id,
  123. llvm::DenseMap<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces,
  124. SemIR::ImportIRId ir_id, SemIR::InstId import_inst_id,
  125. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId enclosing_scope_id,
  126. SemIR::NameId name_id) -> SemIR::NameScopeId {
  127. // Produce the namespace for the entry.
  128. auto make_import_id = [&]() {
  129. auto import_ir_inst_id = context.import_ir_insts().Add(
  130. {.ir_id = ir_id, .inst_id = import_inst_id});
  131. return context.AddInst(SemIR::ImportRefLoaded{
  132. .type_id = namespace_type_id, .import_ir_inst_id = import_ir_inst_id});
  133. };
  134. auto [namespace_scope_id, namespace_const_id, _] =
  135. AddNamespace(context, namespace_type_id, Parse::NodeId::Invalid, name_id,
  136. enclosing_scope_id, /*diagnose_duplicate_namespace=*/false,
  137. make_import_id);
  138. context.import_ir_constant_values()[ir_id.index].Set(import_inst_id,
  139. namespace_const_id);
  140. CacheCopiedNamespace(copied_namespaces, import_scope_id, namespace_scope_id);
  141. return namespace_scope_id;
  142. }
  143. // Copies enclosing name scopes from the import IR. Handles the parent
  144. // traversal. Returns the NameScope corresponding to the copied
  145. // import_enclosing_scope_id.
  146. static auto CopyEnclosingNameScopesFromImportIR(
  147. Context& context, SemIR::TypeId namespace_type_id,
  148. const SemIR::File& import_sem_ir, SemIR::ImportIRId ir_id,
  149. SemIR::NameScopeId import_enclosing_scope_id,
  150. llvm::DenseMap<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces)
  151. -> SemIR::NameScopeId {
  152. // Package-level names don't need work.
  153. if (import_enclosing_scope_id == SemIR::NameScopeId::Package) {
  154. return import_enclosing_scope_id;
  155. }
  156. // The scope to add namespaces to. Note this may change while looking at
  157. // enclosing scopes, if we encounter a namespace that's already added.
  158. auto scope_cursor = SemIR::NameScopeId::Package;
  159. // Build a stack of enclosing namespace names, with innermost first.
  160. llvm::SmallVector<SemIR::NameScopeId> new_namespaces;
  161. while (import_enclosing_scope_id != SemIR::NameScopeId::Package) {
  162. // If the namespace was already copied, reuse the results.
  163. if (auto it = copied_namespaces.find(import_enclosing_scope_id);
  164. it != copied_namespaces.end()) {
  165. // We inject names at the provided scope, and don't need to keep
  166. // traversing parents.
  167. scope_cursor = it->second;
  168. break;
  169. }
  170. // The namespace hasn't been copied yet, so add it to our list.
  171. const auto& scope =
  172. import_sem_ir.name_scopes().Get(import_enclosing_scope_id);
  173. auto scope_inst =
  174. import_sem_ir.insts().GetAs<SemIR::Namespace>(scope.inst_id);
  175. new_namespaces.push_back(scope_inst.name_scope_id);
  176. import_enclosing_scope_id = scope.enclosing_scope_id;
  177. }
  178. // Add enclosing namespace names, starting with the outermost.
  179. for (auto import_scope_id : llvm::reverse(new_namespaces)) {
  180. auto import_scope = import_sem_ir.name_scopes().Get(import_scope_id);
  181. auto name_id =
  182. CopyNameFromImportIR(context, import_sem_ir, import_scope.name_id);
  183. scope_cursor = CopySingleNameScopeFromImportIR(
  184. context, namespace_type_id, copied_namespaces, ir_id,
  185. import_scope.inst_id, import_scope_id, scope_cursor, name_id);
  186. }
  187. return scope_cursor;
  188. }
  189. auto ImportLibraryFromCurrentPackage(Context& context,
  190. SemIR::TypeId namespace_type_id,
  191. Parse::ImportDirectiveId node_id,
  192. bool is_api_for_impl,
  193. const SemIR::File& import_sem_ir) -> void {
  194. auto ir_id = SemIR::ImportIRId::Invalid;
  195. if (is_api_for_impl) {
  196. ir_id = SemIR::ImportIRId::ApiForImpl;
  197. auto& import_ir = context.import_irs().Get(ir_id);
  198. CARBON_CHECK(import_ir.sem_ir == nullptr) << "ApiForImpl is only set once";
  199. import_ir = {.node_id = node_id, .sem_ir = &import_sem_ir};
  200. } else {
  201. ir_id = context.import_irs().Add(
  202. {.node_id = node_id, .sem_ir = &import_sem_ir});
  203. }
  204. context.import_ir_constant_values()[ir_id.index].Set(
  205. SemIR::InstId::PackageNamespace,
  206. context.constant_values().Get(SemIR::InstId::PackageNamespace));
  207. for (const auto import_inst_id :
  208. import_sem_ir.inst_blocks().Get(SemIR::InstBlockId::Exports)) {
  209. auto import_inst = import_sem_ir.insts().Get(import_inst_id);
  210. auto [import_name_id, import_enclosing_scope_id] =
  211. GetImportName(import_sem_ir, import_inst);
  212. // TODO: This should only be invalid when GetImportName for an inst
  213. // isn't yet implemented. Long-term this should be removed.
  214. if (!import_name_id.is_valid()) {
  215. continue;
  216. }
  217. llvm::DenseMap<SemIR::NameScopeId, SemIR::NameScopeId> copied_namespaces;
  218. auto name_id = CopyNameFromImportIR(context, import_sem_ir, import_name_id);
  219. SemIR::NameScopeId enclosing_scope_id = CopyEnclosingNameScopesFromImportIR(
  220. context, namespace_type_id, import_sem_ir, ir_id,
  221. import_enclosing_scope_id, copied_namespaces);
  222. if (auto import_namespace_inst = import_inst.TryAs<SemIR::Namespace>()) {
  223. // Namespaces are always imported because they're essential for
  224. // qualifiers, and the type is simple.
  225. CopySingleNameScopeFromImportIR(
  226. context, namespace_type_id, copied_namespaces, ir_id, import_inst_id,
  227. import_namespace_inst->name_scope_id, enclosing_scope_id, name_id);
  228. } else {
  229. // Leave a placeholder that the inst comes from the other IR.
  230. auto target_id =
  231. context.AddImportRef({.ir_id = ir_id, .inst_id = import_inst_id});
  232. auto [it, success] = context.name_scopes()
  233. .Get(enclosing_scope_id)
  234. .names.insert({name_id, target_id});
  235. if (!success) {
  236. MergeImportRef(context, target_id, it->second);
  237. }
  238. }
  239. }
  240. }
  241. auto ImportLibrariesFromOtherPackage(Context& context,
  242. SemIR::TypeId namespace_type_id,
  243. Parse::ImportDirectiveId node_id,
  244. IdentifierId package_id,
  245. llvm::ArrayRef<SemIR::ImportIR> import_irs,
  246. bool has_load_error) -> void {
  247. CARBON_CHECK(has_load_error || !import_irs.empty())
  248. << "There should be either a load error or at least one IR.";
  249. auto name_id = SemIR::NameId::ForIdentifier(package_id);
  250. auto [namespace_scope_id, namespace_const_id, is_duplicate] = AddNamespace(
  251. context, namespace_type_id, node_id, name_id, SemIR::NameScopeId::Package,
  252. /*diagnose_duplicate_namespace=*/true, /*make_import_id=*/std::nullopt);
  253. auto& scope = context.name_scopes().Get(namespace_scope_id);
  254. scope.is_closed_import = !is_duplicate;
  255. for (auto import_ir : import_irs) {
  256. auto ir_id = context.import_irs().Add(import_ir);
  257. scope.import_ir_scopes.push_back({ir_id, SemIR::NameScopeId::Package});
  258. context.import_ir_constant_values()[ir_id.index].Set(
  259. SemIR::InstId::PackageNamespace, namespace_const_id);
  260. }
  261. if (has_load_error) {
  262. scope.has_error = has_load_error;
  263. }
  264. }
  265. } // namespace Carbon::Check