check_unit.cpp 24 KB

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