check_unit.cpp 24 KB

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