import.cpp 15 KB

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