check_unit.cpp 25 KB

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