import.cpp 12 KB

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