import.cpp 12 KB

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