import.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 "common/map.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/check/context.h"
  9. #include "toolchain/check/import_ref.h"
  10. #include "toolchain/check/merge.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/import_ir.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/name_scope.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Returns name information for the entity, corresponding to IDs in the import
  20. // IR rather than the current IR.
  21. static auto GetImportName(const SemIR::File& import_sem_ir,
  22. SemIR::Inst import_inst)
  23. -> std::pair<SemIR::NameId, SemIR::NameScopeId> {
  24. CARBON_KIND_SWITCH(import_inst) {
  25. case SemIR::BindAlias::Kind:
  26. case SemIR::BindName::Kind:
  27. case SemIR::BindSymbolicName::Kind:
  28. case SemIR::ExportDecl::Kind: {
  29. auto bind_inst = import_inst.As<SemIR::AnyBindNameOrExportDecl>();
  30. const auto& bind_name =
  31. import_sem_ir.bind_names().Get(bind_inst.bind_name_id);
  32. return {bind_name.name_id, bind_name.parent_scope_id};
  33. }
  34. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  35. const auto& class_info = import_sem_ir.classes().Get(class_decl.class_id);
  36. return {class_info.name_id, class_info.parent_scope_id};
  37. }
  38. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  39. const auto& function =
  40. import_sem_ir.functions().Get(function_decl.function_id);
  41. return {function.name_id, function.parent_scope_id};
  42. }
  43. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  44. const auto& interface =
  45. import_sem_ir.interfaces().Get(interface_decl.interface_id);
  46. return {interface.name_id, interface.parent_scope_id};
  47. }
  48. case CARBON_KIND(SemIR::Namespace ns): {
  49. const auto& scope = import_sem_ir.name_scopes().Get(ns.name_scope_id);
  50. return {scope.name_id, scope.parent_scope_id};
  51. }
  52. default:
  53. CARBON_FATAL() << "Unsupported export kind: " << import_inst;
  54. }
  55. }
  56. // Translate the name to the current IR. It will usually be an identifier, but
  57. // could also be a builtin name ID which is equivalent cross-IR.
  58. static auto CopyNameFromImportIR(Context& context,
  59. const SemIR::File& import_sem_ir,
  60. SemIR::NameId import_name_id) {
  61. if (auto import_identifier_id = import_name_id.AsIdentifierId();
  62. import_identifier_id.is_valid()) {
  63. auto name = import_sem_ir.identifiers().Get(import_identifier_id);
  64. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  65. }
  66. return import_name_id;
  67. }
  68. // Adds a namespace to the IR. The bool on return is true if there was a name
  69. // conflict. diagnose_duplicate_namespace is used when handling a cross-package
  70. // import, where an existing namespace is in the current package and the new
  71. // namespace is a different package.
  72. static auto AddNamespace(
  73. Context& context, SemIR::TypeId namespace_type_id, SemIR::NameId name_id,
  74. SemIR::NameScopeId parent_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* parent_scope = &context.name_scopes().Get(parent_scope_id);
  78. auto insert_result =
  79. parent_scope->name_map.Insert(name_id, parent_scope->names.size());
  80. if (!insert_result.is_inserted()) {
  81. auto prev_inst_id = parent_scope->names[insert_result.value()].inst_id;
  82. if (auto namespace_inst =
  83. context.insts().TryGetAs<SemIR::Namespace>(prev_inst_id)) {
  84. if (diagnose_duplicate_namespace) {
  85. auto import_id = (*make_import_id)();
  86. CARBON_CHECK(import_id.is_valid());
  87. context.DiagnoseDuplicateName(import_id, prev_inst_id);
  88. }
  89. return {namespace_inst->name_scope_id,
  90. context.constant_values().Get(prev_inst_id), true};
  91. }
  92. }
  93. auto import_id = (*make_import_id)();
  94. CARBON_CHECK(import_id.is_valid());
  95. auto namespace_inst = SemIR::Namespace{
  96. namespace_type_id, SemIR::NameScopeId::Invalid, import_id};
  97. auto namespace_id =
  98. context.AddPlaceholderInst(SemIR::LocIdAndInst::ReusingLoc(
  99. context.insts().GetLocId(import_id), namespace_inst));
  100. namespace_inst.name_scope_id =
  101. context.name_scopes().Add(namespace_id, name_id, parent_scope_id);
  102. context.ReplaceInstBeforeConstantUse(namespace_id, namespace_inst);
  103. // Note we have to get the parent scope freshly, creating the imported
  104. // namespace may invalidate the pointer above.
  105. parent_scope = &context.name_scopes().Get(parent_scope_id);
  106. // Diagnose if there's a name conflict, but still produce the namespace to
  107. // supersede the name conflict in order to avoid repeat diagnostics.
  108. if (!insert_result.is_inserted()) {
  109. auto& entry = parent_scope->names[insert_result.value()];
  110. context.DiagnoseDuplicateName(namespace_id, entry.inst_id);
  111. entry.inst_id = namespace_id;
  112. entry.access_kind = SemIR::AccessKind::Public;
  113. } else {
  114. parent_scope->names.push_back({.name_id = name_id,
  115. .inst_id = namespace_id,
  116. .access_kind = SemIR::AccessKind::Public});
  117. }
  118. return {namespace_inst.name_scope_id,
  119. context.constant_values().Get(namespace_id), false};
  120. }
  121. // Adds a copied namespace to the cache.
  122. static auto CacheCopiedNamespace(
  123. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces,
  124. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId to_scope_id)
  125. -> void {
  126. auto result = copied_namespaces.Insert(import_scope_id, to_scope_id);
  127. CARBON_CHECK(result.is_inserted() || result.value() == to_scope_id)
  128. << "Copy result for namespace changed from " << import_scope_id << " to "
  129. << to_scope_id;
  130. }
  131. // Copies a namespace from the import IR, returning its ID. This may diagnose
  132. // name conflicts, but that won't change the result because namespaces supersede
  133. // other names in conflicts. copied_namespaces is optional.
  134. static auto CopySingleNameScopeFromImportIR(
  135. Context& context, SemIR::TypeId namespace_type_id,
  136. Map<SemIR::NameScopeId, SemIR::NameScopeId>* copied_namespaces,
  137. SemIR::ImportIRId ir_id, SemIR::InstId import_inst_id,
  138. SemIR::NameScopeId import_scope_id, SemIR::NameScopeId parent_scope_id,
  139. SemIR::NameId name_id) -> SemIR::NameScopeId {
  140. // Produce the namespace for the entry.
  141. auto make_import_id = [&]() {
  142. auto bind_name_id = context.bind_names().Add(
  143. {.name_id = name_id,
  144. .parent_scope_id = parent_scope_id,
  145. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  146. auto import_ir_inst_id = context.import_ir_insts().Add(
  147. {.ir_id = ir_id, .inst_id = import_inst_id});
  148. return context.AddInst<SemIR::ImportRefLoaded>(
  149. import_ir_inst_id, {.type_id = namespace_type_id,
  150. .import_ir_inst_id = import_ir_inst_id,
  151. .bind_name_id = bind_name_id});
  152. };
  153. auto [namespace_scope_id, namespace_const_id, _] =
  154. AddNamespace(context, namespace_type_id, name_id, parent_scope_id,
  155. /*diagnose_duplicate_namespace=*/false, make_import_id);
  156. context.import_ir_constant_values()[ir_id.index].Set(import_inst_id,
  157. namespace_const_id);
  158. if (copied_namespaces) {
  159. CacheCopiedNamespace(*copied_namespaces, import_scope_id,
  160. namespace_scope_id);
  161. }
  162. return namespace_scope_id;
  163. }
  164. // Copies ancestor name scopes from the import IR. Handles the parent traversal.
  165. // Returns the NameScope corresponding to the copied import_parent_scope_id.
  166. static auto CopyAncestorNameScopesFromImportIR(
  167. Context& context, SemIR::TypeId namespace_type_id,
  168. const SemIR::File& import_sem_ir, SemIR::ImportIRId ir_id,
  169. SemIR::NameScopeId import_parent_scope_id,
  170. Map<SemIR::NameScopeId, SemIR::NameScopeId>& copied_namespaces)
  171. -> SemIR::NameScopeId {
  172. // Package-level names don't need work.
  173. if (import_parent_scope_id == SemIR::NameScopeId::Package) {
  174. return import_parent_scope_id;
  175. }
  176. // The scope to add namespaces to. Note this may change while looking at
  177. // parent scopes, if we encounter a namespace that's already added.
  178. auto scope_cursor = SemIR::NameScopeId::Package;
  179. // Build a stack of ancestor namespace names, with the immediate parent first.
  180. llvm::SmallVector<SemIR::NameScopeId> new_namespaces;
  181. while (import_parent_scope_id != SemIR::NameScopeId::Package) {
  182. // If the namespace was already copied, reuse the results.
  183. if (auto result = copied_namespaces.Lookup(import_parent_scope_id)) {
  184. // We inject names at the provided scope, and don't need to keep
  185. // traversing parents.
  186. scope_cursor = result.value();
  187. break;
  188. }
  189. // The namespace hasn't been copied yet, so add it to our list.
  190. const auto& scope = import_sem_ir.name_scopes().Get(import_parent_scope_id);
  191. auto scope_inst =
  192. import_sem_ir.insts().GetAs<SemIR::Namespace>(scope.inst_id);
  193. new_namespaces.push_back(scope_inst.name_scope_id);
  194. import_parent_scope_id = scope.parent_scope_id;
  195. }
  196. // Add ancestor namespace names, starting with the outermost.
  197. for (auto import_scope_id : llvm::reverse(new_namespaces)) {
  198. auto import_scope = import_sem_ir.name_scopes().Get(import_scope_id);
  199. auto name_id =
  200. CopyNameFromImportIR(context, import_sem_ir, import_scope.name_id);
  201. scope_cursor = CopySingleNameScopeFromImportIR(
  202. context, namespace_type_id, &copied_namespaces, ir_id,
  203. import_scope.inst_id, import_scope_id, scope_cursor, name_id);
  204. }
  205. return scope_cursor;
  206. }
  207. // Adds an ImportRef for an entity, handling merging if needed.
  208. static auto AddImportRefOrMerge(Context& context, SemIR::ImportIRId ir_id,
  209. const SemIR::File& import_sem_ir,
  210. SemIR::InstId import_inst_id,
  211. SemIR::NameScopeId parent_scope_id,
  212. SemIR::NameId name_id) -> void {
  213. // Leave a placeholder that the inst comes from the other IR.
  214. auto& parent_scope = context.name_scopes().Get(parent_scope_id);
  215. auto insert = parent_scope.name_map.Insert(name_id, [&] {
  216. auto bind_name_id = context.bind_names().Add(
  217. {.name_id = name_id,
  218. .parent_scope_id = parent_scope_id,
  219. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  220. int index = parent_scope.names.size();
  221. parent_scope.names.push_back(
  222. {.name_id = name_id,
  223. .inst_id =
  224. AddImportRef(context, {.ir_id = ir_id, .inst_id = import_inst_id},
  225. bind_name_id),
  226. .access_kind = SemIR::AccessKind::Public});
  227. return index;
  228. });
  229. if (insert.is_inserted()) {
  230. return;
  231. }
  232. auto inst_id = parent_scope.names[insert.value()].inst_id;
  233. auto prev_ir_inst =
  234. GetCanonicalImportIRInst(context, &context.sem_ir(), inst_id);
  235. VerifySameCanonicalImportIRInst(context, inst_id, prev_ir_inst, ir_id,
  236. &import_sem_ir, import_inst_id);
  237. }
  238. namespace {
  239. // A scope in the API file that still needs to be copied to the implementation
  240. // file. Only used for API file imports.
  241. struct TodoScope {
  242. // The scope's instruction in the API file.
  243. SemIR::InstId api_inst_id;
  244. // The scope in the API file.
  245. SemIR::NameScopeId api_scope_id;
  246. // The already-translated scope name in the implementation file.
  247. SemIR::NameId impl_name_id;
  248. // The already-copied parent scope in the implementation file.
  249. SemIR::NameScopeId impl_parent_scope_id;
  250. };
  251. } // namespace
  252. // Imports entries in a specific scope into the current file.
  253. static auto ImportScopeFromApiFile(Context& context,
  254. const SemIR::File& api_sem_ir,
  255. SemIR::NameScopeId api_scope_id,
  256. SemIR::NameScopeId impl_scope_id,
  257. llvm::SmallVector<TodoScope>& todo_scopes)
  258. -> void {
  259. const auto& api_scope = api_sem_ir.name_scopes().Get(api_scope_id);
  260. auto& impl_scope = context.name_scopes().Get(impl_scope_id);
  261. for (const auto& api_entry : api_scope.names) {
  262. auto impl_name_id =
  263. CopyNameFromImportIR(context, api_sem_ir, api_entry.name_id);
  264. if (auto ns =
  265. api_sem_ir.insts().TryGetAs<SemIR::Namespace>(api_entry.inst_id)) {
  266. // Ignore cross-package imports. These will be handled through
  267. // ImportLibrariesFromOtherPackage.
  268. if (api_scope_id == SemIR::NameScopeId::Package) {
  269. const auto& ns_scope = api_sem_ir.name_scopes().Get(ns->name_scope_id);
  270. if (!ns_scope.import_ir_scopes.empty()) {
  271. continue;
  272. }
  273. }
  274. // Namespaces will be recursed into. Name scope creation is delayed in
  275. // order to avoid invalidating api_scope/impl_scope.
  276. todo_scopes.push_back({.api_inst_id = api_entry.inst_id,
  277. .api_scope_id = ns->name_scope_id,
  278. .impl_name_id = impl_name_id,
  279. .impl_parent_scope_id = impl_scope_id});
  280. } else {
  281. // Add an ImportRef for other instructions.
  282. auto impl_bind_name_id = context.bind_names().Add(
  283. {.name_id = impl_name_id,
  284. .parent_scope_id = impl_scope_id,
  285. .bind_index = SemIR::CompileTimeBindIndex::Invalid});
  286. auto import_ref_id = AddImportRef(context,
  287. {.ir_id = SemIR::ImportIRId::ApiForImpl,
  288. .inst_id = api_entry.inst_id},
  289. impl_bind_name_id);
  290. impl_scope.AddRequired({.name_id = impl_name_id,
  291. .inst_id = import_ref_id,
  292. .access_kind = api_entry.access_kind});
  293. }
  294. }
  295. }
  296. auto ImportApiFile(Context& context, SemIR::TypeId namespace_type_id,
  297. const SemIR::File& api_sem_ir) -> void {
  298. context.import_ir_constant_values()[SemIR::ImportIRId::ApiForImpl.index].Set(
  299. SemIR::InstId::PackageNamespace,
  300. context.constant_values().Get(SemIR::InstId::PackageNamespace));
  301. llvm::SmallVector<TodoScope> todo_scopes = {};
  302. ImportScopeFromApiFile(context, api_sem_ir, SemIR::NameScopeId::Package,
  303. SemIR::NameScopeId::Package, todo_scopes);
  304. while (!todo_scopes.empty()) {
  305. auto todo_scope = todo_scopes.pop_back_val();
  306. auto impl_scope_id = CopySingleNameScopeFromImportIR(
  307. context, namespace_type_id, /*copied_namespaces=*/nullptr,
  308. SemIR::ImportIRId::ApiForImpl, todo_scope.api_inst_id,
  309. todo_scope.api_scope_id, todo_scope.impl_parent_scope_id,
  310. todo_scope.impl_name_id);
  311. ImportScopeFromApiFile(context, api_sem_ir, todo_scope.api_scope_id,
  312. impl_scope_id, todo_scopes);
  313. }
  314. }
  315. auto ImportLibrariesFromCurrentPackage(
  316. Context& context, SemIR::TypeId namespace_type_id,
  317. llvm::ArrayRef<SemIR::ImportIR> import_irs) -> void {
  318. for (auto import_ir : import_irs) {
  319. auto ir_id = AddImportIR(context, import_ir);
  320. context.import_ir_constant_values()[ir_id.index].Set(
  321. SemIR::InstId::PackageNamespace,
  322. context.constant_values().Get(SemIR::InstId::PackageNamespace));
  323. for (const auto import_inst_id :
  324. import_ir.sem_ir->inst_blocks().Get(SemIR::InstBlockId::Exports)) {
  325. auto import_inst = import_ir.sem_ir->insts().Get(import_inst_id);
  326. auto [import_name_id, import_parent_scope_id] =
  327. GetImportName(*import_ir.sem_ir, import_inst);
  328. Map<SemIR::NameScopeId, SemIR::NameScopeId> copied_namespaces;
  329. auto name_id =
  330. CopyNameFromImportIR(context, *import_ir.sem_ir, import_name_id);
  331. SemIR::NameScopeId parent_scope_id = CopyAncestorNameScopesFromImportIR(
  332. context, namespace_type_id, *import_ir.sem_ir, ir_id,
  333. import_parent_scope_id, copied_namespaces);
  334. if (auto import_namespace_inst = import_inst.TryAs<SemIR::Namespace>()) {
  335. // Namespaces are always imported because they're essential for
  336. // qualifiers, and the type is simple.
  337. CopySingleNameScopeFromImportIR(
  338. context, namespace_type_id, &copied_namespaces, ir_id,
  339. import_inst_id, import_namespace_inst->name_scope_id,
  340. parent_scope_id, name_id);
  341. } else {
  342. AddImportRefOrMerge(context, ir_id, *import_ir.sem_ir, import_inst_id,
  343. parent_scope_id, name_id);
  344. }
  345. }
  346. // If an import of the current package caused an error for the imported
  347. // file, it transitively affects the current file too.
  348. if (import_ir.sem_ir->name_scopes()
  349. .Get(SemIR::NameScopeId::Package)
  350. .has_error) {
  351. context.name_scopes().Get(SemIR::NameScopeId::Package).has_error = true;
  352. }
  353. }
  354. }
  355. auto ImportLibrariesFromOtherPackage(Context& context,
  356. SemIR::TypeId namespace_type_id,
  357. SemIR::InstId import_decl_id,
  358. IdentifierId package_id,
  359. llvm::ArrayRef<SemIR::ImportIR> import_irs,
  360. bool has_load_error) -> void {
  361. CARBON_CHECK(has_load_error || !import_irs.empty())
  362. << "There should be either a load error or at least one IR.";
  363. auto name_id = SemIR::NameId::ForIdentifier(package_id);
  364. auto [namespace_scope_id, namespace_const_id, is_duplicate] = AddNamespace(
  365. context, namespace_type_id, name_id, SemIR::NameScopeId::Package,
  366. /*diagnose_duplicate_namespace=*/true, [&] { return import_decl_id; });
  367. auto& scope = context.name_scopes().Get(namespace_scope_id);
  368. scope.is_closed_import = !is_duplicate;
  369. for (auto import_ir : import_irs) {
  370. auto ir_id = AddImportIR(context, import_ir);
  371. scope.import_ir_scopes.push_back({ir_id, SemIR::NameScopeId::Package});
  372. context.import_ir_constant_values()[ir_id.index].Set(
  373. SemIR::InstId::PackageNamespace, namespace_const_id);
  374. }
  375. if (has_load_error) {
  376. scope.has_error = has_load_error;
  377. }
  378. }
  379. } // namespace Carbon::Check