check_unit.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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/check_unit.h"
  5. #include <string>
  6. #include <utility>
  7. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  8. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/Support/VirtualFileSystem.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/base/pretty_stack_trace_function.h"
  12. #include "toolchain/check/diagnostic_helpers.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/handle.h"
  15. #include "toolchain/check/impl.h"
  16. #include "toolchain/check/impl_lookup.h"
  17. #include "toolchain/check/import.h"
  18. #include "toolchain/check/import_cpp.h"
  19. #include "toolchain/check/import_ref.h"
  20. #include "toolchain/check/inst.h"
  21. #include "toolchain/check/node_id_traversal.h"
  22. #include "toolchain/check/type.h"
  23. #include "toolchain/check/type_structure.h"
  24. #include "toolchain/diagnostics/diagnostic.h"
  25. #include "toolchain/sem_ir/function.h"
  26. #include "toolchain/sem_ir/ids.h"
  27. #include "toolchain/sem_ir/import_ir.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Returns the number of imported IRs, to assist in Context construction.
  31. static auto GetImportedIRCount(UnitAndImports* unit_and_imports) -> int {
  32. int count = 0;
  33. for (auto& package_imports : unit_and_imports->package_imports) {
  34. count += package_imports.imports.size();
  35. }
  36. if (!unit_and_imports->api_for_impl) {
  37. // Leave an empty slot for `ImportIRId::ApiForImpl`.
  38. ++count;
  39. }
  40. if (!unit_and_imports->cpp_import_names.empty()) {
  41. // Leave an empty slot for `ImportIRId::Cpp`.
  42. ++count;
  43. }
  44. return count;
  45. }
  46. CheckUnit::CheckUnit(
  47. UnitAndImports* unit_and_imports,
  48. llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> tree_and_subtrees_getters,
  49. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  50. llvm::raw_ostream* vlog_stream)
  51. : unit_and_imports_(unit_and_imports),
  52. tree_and_subtrees_getter_(
  53. tree_and_subtrees_getters
  54. [unit_and_imports->unit->sem_ir->check_ir_id().index]),
  55. total_ir_count_(tree_and_subtrees_getters.size()),
  56. fs_(std::move(fs)),
  57. vlog_stream_(vlog_stream),
  58. emitter_(&unit_and_imports_->err_tracker, tree_and_subtrees_getters,
  59. unit_and_imports_->unit->sem_ir),
  60. context_(
  61. &emitter_, tree_and_subtrees_getter_, unit_and_imports_->unit->sem_ir,
  62. GetImportedIRCount(unit_and_imports), total_ir_count_, vlog_stream) {}
  63. auto CheckUnit::Run() -> void {
  64. Timings::ScopedTiming timing(unit_and_imports_->unit->timings, "check");
  65. // We can safely mark this as checked at the start.
  66. unit_and_imports_->is_checked = true;
  67. PrettyStackTraceFunction context_dumper(
  68. [&](llvm::raw_ostream& output) { context_.PrintForStackDump(output); });
  69. // Add a block for the file.
  70. context_.inst_block_stack().Push();
  71. InitPackageScopeAndImports();
  72. // Eagerly import the impls declared in the api file to prepare to redeclare
  73. // them.
  74. ImportImplsFromApiFile(context_);
  75. if (!ProcessNodeIds()) {
  76. context_.sem_ir().set_has_errors(true);
  77. return;
  78. }
  79. FinishRun();
  80. }
  81. auto CheckUnit::InitPackageScopeAndImports() -> void {
  82. // Importing makes many namespaces, so only canonicalize the type once.
  83. auto namespace_type_id =
  84. GetSingletonType(context_, SemIR::NamespaceType::TypeInstId);
  85. // Define the package scope, with an instruction for `package` expressions to
  86. // reference.
  87. auto package_scope_id = context_.name_scopes().Add(
  88. SemIR::Namespace::PackageInstId, SemIR::NameId::PackageNamespace,
  89. SemIR::NameScopeId::None);
  90. CARBON_CHECK(package_scope_id == SemIR::NameScopeId::Package);
  91. auto package_inst_id =
  92. AddInst<SemIR::Namespace>(context_, Parse::NodeId::None,
  93. {.type_id = namespace_type_id,
  94. .name_scope_id = SemIR::NameScopeId::Package,
  95. .import_id = SemIR::InstId::None});
  96. CARBON_CHECK(package_inst_id == SemIR::Namespace::PackageInstId);
  97. // Call `SetSpecialImportIRs()` to set `ImportIRId::ApiForImpl` and
  98. // `ImportIRId::Cpp` first, as required.
  99. if (unit_and_imports_->api_for_impl) {
  100. const auto& names = context_.parse_tree().packaging_decl()->names;
  101. auto import_decl_id = AddInst<SemIR::ImportDecl>(
  102. context_, names.node_id,
  103. {.package_id = SemIR::NameId::ForPackageName(names.package_id)});
  104. SetSpecialImportIRs(
  105. context_, {.decl_id = import_decl_id,
  106. .is_export = false,
  107. .sem_ir = unit_and_imports_->api_for_impl->unit->sem_ir});
  108. } else {
  109. SetSpecialImportIRs(context_,
  110. {.decl_id = SemIR::InstId::None, .sem_ir = nullptr});
  111. }
  112. // Add import instructions for everything directly imported. Implicit imports
  113. // are handled separately.
  114. for (auto& package_imports : unit_and_imports_->package_imports) {
  115. CARBON_CHECK(!package_imports.import_decl_id.has_value());
  116. package_imports.import_decl_id = AddInst<SemIR::ImportDecl>(
  117. context_, package_imports.node_id,
  118. {.package_id =
  119. SemIR::NameId::ForPackageName(package_imports.package_id)});
  120. }
  121. // Process the imports.
  122. if (unit_and_imports_->api_for_impl) {
  123. ImportApiFile(context_, namespace_type_id,
  124. *unit_and_imports_->api_for_impl->unit->sem_ir);
  125. }
  126. ImportCurrentPackage(package_inst_id, namespace_type_id);
  127. CARBON_CHECK(context_.scope_stack().PeekIndex() == ScopeIndex::Package);
  128. ImportOtherPackages(namespace_type_id);
  129. const auto& cpp_import_names = unit_and_imports_->cpp_import_names;
  130. if (!cpp_import_names.empty()) {
  131. auto* cpp_ast = unit_and_imports_->unit->cpp_ast;
  132. CARBON_CHECK(cpp_ast);
  133. CARBON_CHECK(!cpp_ast->get());
  134. *cpp_ast =
  135. ImportCppFiles(context_, unit_and_imports_->unit->sem_ir->filename(),
  136. cpp_import_names, fs_);
  137. }
  138. }
  139. auto CheckUnit::CollectDirectImports(
  140. llvm::SmallVector<SemIR::ImportIR>& results,
  141. llvm::MutableArrayRef<int> ir_to_result_index, SemIR::InstId import_decl_id,
  142. const PackageImports& imports, bool is_local) -> void {
  143. for (const auto& import : imports.imports) {
  144. const auto& direct_ir = *import.unit_info->unit->sem_ir;
  145. auto& index = ir_to_result_index[direct_ir.check_ir_id().index];
  146. if (index != -1) {
  147. // This should only happen when doing API imports for an implementation
  148. // file. Don't change the entry; is_export doesn't matter.
  149. continue;
  150. }
  151. index = results.size();
  152. results.push_back({.decl_id = import_decl_id,
  153. // Only tag exports in API files, ignoring the value in
  154. // implementation files.
  155. .is_export = is_local && import.names.is_export,
  156. .sem_ir = &direct_ir});
  157. }
  158. }
  159. auto CheckUnit::CollectTransitiveImports(SemIR::InstId import_decl_id,
  160. const PackageImports* local_imports,
  161. const PackageImports* api_imports)
  162. -> llvm::SmallVector<SemIR::ImportIR> {
  163. llvm::SmallVector<SemIR::ImportIR> results;
  164. // Track whether an IR was imported in full, including `export import`. This
  165. // distinguishes from IRs that are indirectly added without all names being
  166. // exported to this IR.
  167. llvm::SmallVector<int> ir_to_result_index(total_ir_count_, -1);
  168. // First add direct imports. This means that if an entity is imported both
  169. // directly and indirectly, the import path will reflect the direct import.
  170. if (local_imports) {
  171. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  172. *local_imports,
  173. /*is_local=*/true);
  174. }
  175. if (api_imports) {
  176. CollectDirectImports(results, ir_to_result_index, import_decl_id,
  177. *api_imports,
  178. /*is_local=*/false);
  179. }
  180. // Loop through direct imports for any indirect exports. The underlying vector
  181. // is appended during iteration, so take the size first.
  182. const int direct_imports = results.size();
  183. for (int direct_index : llvm::seq(direct_imports)) {
  184. bool is_export = results[direct_index].is_export;
  185. for (const auto& indirect_ir :
  186. results[direct_index].sem_ir->import_irs().array_ref()) {
  187. if (!indirect_ir.is_export) {
  188. continue;
  189. }
  190. auto& indirect_index =
  191. ir_to_result_index[indirect_ir.sem_ir->check_ir_id().index];
  192. if (indirect_index == -1) {
  193. indirect_index = results.size();
  194. // TODO: In the case of a recursive `export import`, this only points at
  195. // the outermost import. May want something that better reflects the
  196. // recursion.
  197. results.push_back({.decl_id = results[direct_index].decl_id,
  198. .is_export = is_export,
  199. .sem_ir = indirect_ir.sem_ir});
  200. } else if (is_export) {
  201. results[indirect_index].is_export = true;
  202. }
  203. }
  204. }
  205. return results;
  206. }
  207. auto CheckUnit::ImportCurrentPackage(SemIR::InstId package_inst_id,
  208. SemIR::TypeId namespace_type_id) -> void {
  209. // Add imports from the current package.
  210. auto import_map_lookup =
  211. unit_and_imports_->package_imports_map.Lookup(PackageNameId::None);
  212. if (!import_map_lookup) {
  213. // Push the scope; there are no names to add.
  214. context_.scope_stack().PushForEntity(
  215. package_inst_id, SemIR::NameScopeId::Package, SemIR::SpecificId::None,
  216. /*lexical_lookup_has_load_error=*/false);
  217. return;
  218. }
  219. PackageImports& self_import =
  220. unit_and_imports_->package_imports[import_map_lookup.value()];
  221. if (self_import.has_load_error) {
  222. context_.name_scopes().Get(SemIR::NameScopeId::Package).set_has_error();
  223. }
  224. ImportLibrariesFromCurrentPackage(
  225. context_, namespace_type_id,
  226. CollectTransitiveImports(self_import.import_decl_id, &self_import,
  227. /*api_imports=*/nullptr));
  228. context_.scope_stack().PushForEntity(
  229. package_inst_id, SemIR::NameScopeId::Package, SemIR::SpecificId::None,
  230. context_.name_scopes().Get(SemIR::NameScopeId::Package).has_error());
  231. }
  232. auto CheckUnit::ImportOtherPackages(SemIR::TypeId namespace_type_id) -> void {
  233. // api_imports_list is initially the size of the current file's imports,
  234. // including for API files, for simplicity in iteration. It's only really used
  235. // when processing an implementation file, in order to combine the API file
  236. // imports.
  237. //
  238. // For packages imported by the API file, the PackageNameId is the package
  239. // name and the index is into the API's import list. Otherwise, the initial
  240. // {None, -1} state remains.
  241. llvm::SmallVector<std::pair<PackageNameId, int32_t>> api_imports_list;
  242. api_imports_list.resize(unit_and_imports_->package_imports.size(),
  243. {PackageNameId::None, -1});
  244. // When there's an API file, add the mapping to api_imports_list.
  245. if (unit_and_imports_->api_for_impl) {
  246. const auto& api_identifiers =
  247. unit_and_imports_->api_for_impl->unit->value_stores->identifiers();
  248. auto& impl_identifiers =
  249. unit_and_imports_->unit->value_stores->identifiers();
  250. for (auto [api_imports_index, api_imports] :
  251. llvm::enumerate(unit_and_imports_->api_for_impl->package_imports)) {
  252. // Skip the current package.
  253. if (!api_imports.package_id.has_value()) {
  254. continue;
  255. }
  256. // Translate the package ID from the API file to the implementation file.
  257. auto impl_package_id = api_imports.package_id;
  258. if (auto package_identifier_id = impl_package_id.AsIdentifierId();
  259. package_identifier_id.has_value()) {
  260. impl_package_id = PackageNameId::ForIdentifier(
  261. impl_identifiers.Add(api_identifiers.Get(package_identifier_id)));
  262. }
  263. if (auto lookup =
  264. unit_and_imports_->package_imports_map.Lookup(impl_package_id)) {
  265. // On a hit, replace the entry to unify the API and implementation
  266. // imports.
  267. api_imports_list[lookup.value()] = {impl_package_id, api_imports_index};
  268. } else {
  269. // On a miss, add the package as API-only.
  270. api_imports_list.push_back({impl_package_id, api_imports_index});
  271. }
  272. }
  273. }
  274. for (auto [i, api_imports_entry] : llvm::enumerate(api_imports_list)) {
  275. // These variables are updated after figuring out which imports are present.
  276. auto import_decl_id = SemIR::InstId::None;
  277. PackageNameId package_id = PackageNameId::None;
  278. bool has_load_error = false;
  279. // Identify the local package imports if present.
  280. PackageImports* local_imports = nullptr;
  281. if (i < unit_and_imports_->package_imports.size()) {
  282. local_imports = &unit_and_imports_->package_imports[i];
  283. if (!local_imports->package_id.has_value()) {
  284. // Skip the current package.
  285. continue;
  286. }
  287. import_decl_id = local_imports->import_decl_id;
  288. package_id = local_imports->package_id;
  289. has_load_error |= local_imports->has_load_error;
  290. }
  291. // Identify the API package imports if present.
  292. PackageImports* api_imports = nullptr;
  293. if (api_imports_entry.second != -1) {
  294. api_imports = &unit_and_imports_->api_for_impl
  295. ->package_imports[api_imports_entry.second];
  296. if (local_imports) {
  297. CARBON_CHECK(package_id == api_imports_entry.first);
  298. } else {
  299. auto import_ir_inst_id =
  300. context_.import_ir_insts().Add(SemIR::ImportIRInst(
  301. SemIR::ImportIRId::ApiForImpl, api_imports->import_decl_id));
  302. import_decl_id =
  303. AddInst(context_, MakeImportedLocIdAndInst<SemIR::ImportDecl>(
  304. context_, import_ir_inst_id,
  305. {.package_id = SemIR::NameId::ForPackageName(
  306. api_imports_entry.first)}));
  307. package_id = api_imports_entry.first;
  308. }
  309. has_load_error |= api_imports->has_load_error;
  310. }
  311. // Do the actual import.
  312. ImportLibrariesFromOtherPackage(
  313. context_, namespace_type_id, import_decl_id, package_id,
  314. CollectTransitiveImports(import_decl_id, local_imports, api_imports),
  315. has_load_error);
  316. }
  317. }
  318. // Loops over all nodes in the tree. On some errors, this may return early,
  319. // for example if an unrecoverable state is encountered.
  320. // NOLINTNEXTLINE(readability-function-size)
  321. auto CheckUnit::ProcessNodeIds() -> bool {
  322. NodeIdTraversal traversal(&context_, vlog_stream_);
  323. Parse::NodeId node_id = Parse::NodeId::None;
  324. // On crash, report which token we were handling.
  325. PrettyStackTraceFunction node_dumper([&](llvm::raw_ostream& output) {
  326. const auto& tree = tree_and_subtrees_getter_();
  327. auto converted = tree.NodeToDiagnosticLoc(node_id, /*token_only=*/false);
  328. converted.loc.FormatLocation(output);
  329. output << "checking " << context_.parse_tree().node_kind(node_id) << "\n";
  330. // Crash output has a tab indent; try to indent slightly past that.
  331. converted.loc.FormatSnippet(output, /*indent=*/10);
  332. });
  333. while (auto maybe_node_id = traversal.Next()) {
  334. node_id = *maybe_node_id;
  335. emitter_.AdvanceToken(context_.parse_tree().node_token(node_id));
  336. if (context_.parse_tree().node_has_error(node_id)) {
  337. context_.TODO(node_id, "handle invalid parse trees in `check`");
  338. return false;
  339. }
  340. bool result;
  341. auto parse_kind = context_.parse_tree().node_kind(node_id);
  342. switch (parse_kind) {
  343. #define CARBON_PARSE_NODE_KIND(Name) \
  344. case Parse::NodeKind::Name: { \
  345. result = HandleParseNode( \
  346. context_, context_.parse_tree().As<Parse::Name##Id>(node_id)); \
  347. break; \
  348. }
  349. #include "toolchain/parse/node_kind.def"
  350. }
  351. if (!result) {
  352. CARBON_CHECK(
  353. unit_and_imports_->err_tracker.seen_error(),
  354. "HandleParseNode for `{0}` returned false without diagnosing.",
  355. parse_kind);
  356. return false;
  357. }
  358. traversal.Handle(parse_kind);
  359. }
  360. return true;
  361. }
  362. auto CheckUnit::CheckRequiredDeclarations() -> void {
  363. for (const auto& function : context_.functions().array_ref()) {
  364. if (!function.first_owning_decl_id.has_value() &&
  365. function.extern_library_id == context_.sem_ir().library_id()) {
  366. auto function_import_id =
  367. context_.insts().GetImportSource(function.non_owning_decl_id);
  368. CARBON_CHECK(function_import_id.has_value());
  369. auto import_ir_id =
  370. context_.sem_ir().import_ir_insts().Get(function_import_id).ir_id();
  371. auto& import_ir = context_.import_irs().Get(import_ir_id);
  372. if (import_ir.sem_ir->package_id().has_value() !=
  373. context_.sem_ir().package_id().has_value()) {
  374. continue;
  375. }
  376. CARBON_DIAGNOSTIC(
  377. MissingOwningDeclarationInApi, Error,
  378. "owning declaration required for non-owning declaration");
  379. if (!import_ir.sem_ir->package_id().has_value() &&
  380. !context_.sem_ir().package_id().has_value()) {
  381. emitter_.Emit(function.non_owning_decl_id,
  382. MissingOwningDeclarationInApi);
  383. continue;
  384. }
  385. if (import_ir.sem_ir->identifiers().Get(
  386. import_ir.sem_ir->package_id().AsIdentifierId()) ==
  387. context_.sem_ir().identifiers().Get(
  388. context_.sem_ir().package_id().AsIdentifierId())) {
  389. emitter_.Emit(function.non_owning_decl_id,
  390. MissingOwningDeclarationInApi);
  391. }
  392. }
  393. }
  394. }
  395. auto CheckUnit::CheckRequiredDefinitions() -> void {
  396. CARBON_DIAGNOSTIC(MissingDefinitionInImpl, Error,
  397. "no definition found for declaration in impl file");
  398. // Note that more required definitions can be added during this loop.
  399. // NOLINTNEXTLINE(modernize-loop-convert)
  400. for (size_t i = 0; i != context_.definitions_required_by_decl().size(); ++i) {
  401. SemIR::InstId decl_inst_id = context_.definitions_required_by_decl()[i];
  402. SemIR::Inst decl_inst = context_.insts().Get(decl_inst_id);
  403. CARBON_KIND_SWITCH(context_.insts().Get(decl_inst_id)) {
  404. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  405. if (!context_.classes().Get(class_decl.class_id).is_complete()) {
  406. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  407. }
  408. break;
  409. }
  410. case CARBON_KIND(SemIR::FunctionDecl function_decl): {
  411. if (context_.functions().Get(function_decl.function_id).definition_id ==
  412. SemIR::InstId::None) {
  413. emitter_.Emit(decl_inst_id, MissingDefinitionInImpl);
  414. }
  415. break;
  416. }
  417. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  418. auto& impl = context_.impls().Get(impl_decl.impl_id);
  419. if (!impl.is_complete()) {
  420. FillImplWitnessWithErrors(context_, impl);
  421. CARBON_DIAGNOSTIC(ImplMissingDefinition, Error,
  422. "impl declared but not defined");
  423. emitter_.Emit(decl_inst_id, ImplMissingDefinition);
  424. }
  425. break;
  426. }
  427. case SemIR::InterfaceDecl::Kind: {
  428. // TODO: Handle `interface` as well, once we can test it without
  429. // triggering
  430. // https://github.com/carbon-language/carbon-lang/issues/4071.
  431. CARBON_FATAL("TODO: Support interfaces in DiagnoseMissingDefinitions");
  432. }
  433. default: {
  434. CARBON_FATAL("Unexpected inst in definitions_required_by_decl: {0}",
  435. decl_inst);
  436. }
  437. }
  438. }
  439. // Note that more required definitions can be added during this loop.
  440. // NOLINTNEXTLINE(modernize-loop-convert)
  441. for (size_t i = 0; i != context_.definitions_required_by_use().size(); ++i) {
  442. // This is using the location for the use. We could track the
  443. // list of enclosing locations if this was used from a generic.
  444. auto [loc, specific_id] = context_.definitions_required_by_use()[i];
  445. if (!ResolveSpecificDefinition(context_, loc, specific_id)) {
  446. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinition, Error,
  447. "use of undefined generic function");
  448. CARBON_DIAGNOSTIC(MissingGenericFunctionDefinitionHere, Note,
  449. "generic function declared here");
  450. auto generic_decl_id =
  451. context_.generics()
  452. .Get(context_.specifics().Get(specific_id).generic_id)
  453. .decl_id;
  454. emitter_.Build(loc, MissingGenericFunctionDefinition)
  455. .Note(generic_decl_id, MissingGenericFunctionDefinitionHere)
  456. .Emit();
  457. }
  458. }
  459. }
  460. auto CheckUnit::CheckPoisonedConcreteImplLookupQueries() -> void {
  461. // Impl lookup can generate instructions (via deduce) which we don't use, as
  462. // we're only generating diagnostics here, so we catch and discard them.
  463. context_.inst_block_stack().Push();
  464. auto poisoned_queries =
  465. std::exchange(context_.poisoned_concrete_impl_lookup_queries(), {});
  466. for (const auto& poison : poisoned_queries) {
  467. auto witness_result =
  468. EvalLookupSingleImplWitness(context_, poison.loc_id, poison.query,
  469. poison.non_canonical_query_self_inst_id,
  470. /*poison_concrete_results=*/false);
  471. CARBON_CHECK(witness_result.has_concrete_value());
  472. auto found_witness_id = witness_result.concrete_witness();
  473. if (found_witness_id != poison.impl_witness) {
  474. auto witness_to_impl_id = [&](SemIR::InstId witness_id) {
  475. auto table_id = context_.insts()
  476. .GetAs<SemIR::ImplWitness>(witness_id)
  477. .witness_table_id;
  478. return context_.insts()
  479. .GetAs<SemIR::ImplWitnessTable>(table_id)
  480. .impl_id;
  481. };
  482. // We can get the `Impl` from the resulting witness here, which is the
  483. // `Impl` that conflicts with the previous poison query.
  484. auto bad_impl_id = witness_to_impl_id(found_witness_id);
  485. const auto& bad_impl = context_.impls().Get(bad_impl_id);
  486. auto prev_impl_id = witness_to_impl_id(poison.impl_witness);
  487. const auto& prev_impl = context_.impls().Get(prev_impl_id);
  488. CARBON_DIAGNOSTIC(
  489. PoisonedImplLookupConcreteResult, Error,
  490. "found `impl` that would change the result of an earlier "
  491. "use of `{0} as {1}`",
  492. InstIdAsRawType, SpecificInterfaceIdAsRawType);
  493. auto builder =
  494. emitter_.Build(poison.loc_id, PoisonedImplLookupConcreteResult,
  495. poison.query.query_self_inst_id,
  496. poison.query.query_specific_interface_id);
  497. CARBON_DIAGNOSTIC(
  498. PoisonedImplLookupConcreteResultNoteBadImpl, Note,
  499. "the use would select the `impl` here but it was not found yet");
  500. builder.Note(bad_impl.first_decl_id(),
  501. PoisonedImplLookupConcreteResultNoteBadImpl);
  502. CARBON_DIAGNOSTIC(PoisonedImplLookupConcreteResultNotePreviousImpl, Note,
  503. "the use had selected the `impl` here");
  504. builder.Note(prev_impl.first_decl_id(),
  505. PoisonedImplLookupConcreteResultNotePreviousImpl);
  506. builder.Emit();
  507. }
  508. }
  509. context_.inst_block_stack().PopAndDiscard();
  510. }
  511. auto CheckUnit::CheckOverlappingImpls() -> void {
  512. // Collect all of the impls sorted into contiguous segments by their
  513. // interface. We only need to compare impls within each such segment.
  514. llvm::SmallVector<SemIR::Impl> impls_by_interface(
  515. context_.impls().array_ref());
  516. llvm::stable_sort(
  517. impls_by_interface, [](const SemIR::Impl& a, const SemIR::Impl& b) {
  518. return a.interface.interface_id.index < b.interface.interface_id.index;
  519. });
  520. const auto* it = impls_by_interface.begin();
  521. while (it != impls_by_interface.end()) {
  522. const auto* segment_begin = it;
  523. do {
  524. ++it;
  525. } while (it != impls_by_interface.end() &&
  526. it->interface.interface_id ==
  527. segment_begin->interface.interface_id);
  528. const auto* segment_end = it;
  529. if (std::distance(segment_begin, segment_end) == 1) {
  530. // Only 1 interface in the segment; nothing to overlap with.
  531. continue;
  532. }
  533. CheckOverlappingImplsForInterface(
  534. llvm::ArrayRef(segment_begin, segment_end));
  535. }
  536. }
  537. auto CheckUnit::CheckOverlappingImplsForInterface(
  538. llvm::ArrayRef<SemIR::Impl> impls) -> void {
  539. for (auto [index_a, impl_a] : llvm::enumerate(impls)) {
  540. if (impl_a.witness_id == SemIR::ErrorInst::InstId) {
  541. continue;
  542. }
  543. auto impl_a_type_structure =
  544. BuildTypeStructure(context_, impl_a.self_id, impl_a.interface);
  545. for (const auto& impl_b : impls.drop_front(index_a + 1)) {
  546. if (impl_b.witness_id == SemIR::ErrorInst::InstId) {
  547. continue;
  548. }
  549. // The type structure each non-final `impl` must differ from all other
  550. // non-final `impl` for the same interface visible from the file.
  551. if (!impl_a.is_final && !impl_b.is_final) {
  552. auto impl_b_type_structure =
  553. BuildTypeStructure(context_, impl_b.self_id, impl_b.interface);
  554. if (impl_a_type_structure == impl_b_type_structure) {
  555. CARBON_DIAGNOSTIC(ImplFullyOverlapNonFinal, Error,
  556. "found non-final `impl` that fully overlaps "
  557. "previous non-final `impl`");
  558. auto builder =
  559. emitter_.Build(impl_b.latest_decl_id(), ImplFullyOverlapNonFinal);
  560. CARBON_DIAGNOSTIC(ImplFullyOverlapNonFinalNote, Note,
  561. "fully overlaps `impl` here");
  562. builder.Note(impl_a.latest_decl_id(), ImplFullyOverlapNonFinalNote);
  563. builder.Emit();
  564. break;
  565. }
  566. }
  567. }
  568. // TODO: The self + constraint of a `impl` must not match against (be
  569. // fully subsumed by) any final `impl` visible from the file. Do a
  570. // final-only query for all non-final impls?
  571. }
  572. }
  573. auto CheckUnit::FinishRun() -> void {
  574. CheckRequiredDeclarations();
  575. CheckRequiredDefinitions();
  576. CheckPoisonedConcreteImplLookupQueries();
  577. CheckOverlappingImpls();
  578. // Pop information for the file-level scope.
  579. context_.sem_ir().set_top_inst_block_id(context_.inst_block_stack().Pop());
  580. context_.scope_stack().Pop();
  581. // Finalizes the list of exports on the IR.
  582. context_.inst_blocks().ReplacePlaceholder(SemIR::InstBlockId::Exports,
  583. context_.exports());
  584. // Finalizes the ImportRef inst block.
  585. context_.inst_blocks().ReplacePlaceholder(SemIR::InstBlockId::ImportRefs,
  586. context_.import_ref_ids());
  587. // Finalizes __global_init.
  588. context_.global_init().Finalize();
  589. context_.sem_ir().set_has_errors(unit_and_imports_->err_tracker.seen_error());
  590. // Verify that Context cleanly finished.
  591. context_.VerifyOnFinish();
  592. }
  593. } // namespace Carbon::Check