import.cpp 13 KB

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