impl_validation.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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/impl_validation.h"
  5. #include <utility>
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/check/diagnostic_helpers.h"
  11. #include "toolchain/check/impl_lookup.h"
  12. #include "toolchain/check/import_ref.h"
  13. #include "toolchain/check/type_structure.h"
  14. #include "toolchain/sem_ir/entity_with_params_base.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/type_iterator.h"
  17. namespace Carbon::Check {
  18. namespace {
  19. // All information about a `SemIR::Impl` needed for validation.
  20. struct ImplInfo {
  21. SemIR::ImplId impl_id;
  22. bool is_final;
  23. SemIR::InstId witness_id;
  24. SemIR::TypeInstId self_id;
  25. SemIR::InstId latest_decl_id;
  26. SemIR::SpecificInterface interface;
  27. // Whether the `impl` decl was imported or from the local file.
  28. bool is_local;
  29. // If imported, the IR from which the `impl` decl was imported.
  30. SemIR::ImportIRId ir_id;
  31. TypeStructure type_structure;
  32. };
  33. } // namespace
  34. static auto GetIRId(Context& context, SemIR::InstId owning_inst_id)
  35. -> SemIR::ImportIRId {
  36. if (!owning_inst_id.has_value()) {
  37. return SemIR::ImportIRId::None;
  38. }
  39. return GetCanonicalImportIRInst(context, owning_inst_id).ir_id();
  40. }
  41. auto GetImplInfo(Context& context, SemIR::ImplId impl_id) -> ImplInfo {
  42. const auto& impl = context.impls().Get(impl_id);
  43. auto ir_id = GetIRId(context, impl.first_owning_decl_id);
  44. return {.impl_id = impl_id,
  45. .is_final = impl.is_final,
  46. .witness_id = impl.witness_id,
  47. .self_id = impl.self_id,
  48. .latest_decl_id = impl.latest_decl_id(),
  49. .interface = impl.interface,
  50. .is_local = !ir_id.has_value(),
  51. .ir_id = ir_id,
  52. .type_structure =
  53. BuildTypeStructure(context, impl.self_id, impl.interface)};
  54. }
  55. // A final impl must be in the same file as either its root self type or the
  56. // interface in its constraint.
  57. //
  58. // Returns true if an error was diagnosed.
  59. static auto DiagnoseFinalImplNotInSameFileAsRootSelfTypeOrInterface(
  60. Context& context, const ImplInfo& impl, SemIR::ImportIRId interface_ir_id)
  61. -> bool {
  62. bool self_type_same_file = false;
  63. auto type_iter = SemIR::TypeIterator(&context.sem_ir());
  64. type_iter.Add(impl.self_id);
  65. auto step = type_iter.Next();
  66. using Step = SemIR::TypeIterator::Step;
  67. CARBON_KIND_SWITCH(step.any) {
  68. case CARBON_KIND(Step::ClassStart start): {
  69. auto inst_id = context.classes().Get(start.class_id).first_owning_decl_id;
  70. if (!GetIRId(context, inst_id).has_value()) {
  71. self_type_same_file = true;
  72. }
  73. break;
  74. }
  75. case CARBON_KIND(Step::ClassStartOnly start): {
  76. auto inst_id = context.classes().Get(start.class_id).first_owning_decl_id;
  77. if (!GetIRId(context, inst_id).has_value()) {
  78. self_type_same_file = true;
  79. }
  80. break;
  81. }
  82. case CARBON_KIND(Step::Done _):
  83. CARBON_FATAL("self type is empty?");
  84. default:
  85. break;
  86. }
  87. bool interface_same_file = !interface_ir_id.has_value();
  88. if (!self_type_same_file && !interface_same_file) {
  89. CARBON_DIAGNOSTIC(FinalImplInvalidFile, Error,
  90. "`final impl` found in file that does not contain "
  91. "the root self type nor the interface definition");
  92. context.emitter().Emit(impl.latest_decl_id, FinalImplInvalidFile);
  93. return true;
  94. }
  95. return false;
  96. }
  97. // The type structure each non-final `impl` must differ from all other non-final
  98. // `impl` for the same interface visible from the file.
  99. //
  100. // Returns true if an error was diagnosed.
  101. static auto DiagnoseNonFinalImplsWithSameTypeStructure(Context& context,
  102. const ImplInfo& impl_a,
  103. const ImplInfo& impl_b)
  104. -> bool {
  105. if (impl_a.type_structure == impl_b.type_structure) {
  106. CARBON_DIAGNOSTIC(ImplNonFinalSameTypeStructure, Error,
  107. "found non-final `impl` with the same type "
  108. "structure as another non-final `impl`");
  109. auto builder = context.emitter().Build(impl_b.latest_decl_id,
  110. ImplNonFinalSameTypeStructure);
  111. CARBON_DIAGNOSTIC(ImplNonFinalSameTypeStructureNote, Note,
  112. "other `impl` here");
  113. builder.Note(impl_a.latest_decl_id, ImplNonFinalSameTypeStructureNote);
  114. builder.Emit();
  115. return true;
  116. }
  117. return false;
  118. }
  119. // An impl's self type and constraint can not match (as a lookup query)
  120. // against any final impl, or it would never be used instead of that
  121. // final impl.
  122. //
  123. // Returns true if an error was diagnosed.
  124. static auto DiagnoseUnmatchableNonFinalImplWithFinalImpl(Context& context,
  125. const ImplInfo& impl_a,
  126. const ImplInfo& impl_b)
  127. -> bool {
  128. auto diagnose_unmatchable_impl = [&](const ImplInfo& query_impl,
  129. const ImplInfo& final_impl) -> bool {
  130. if (LookupMatchesImpl(context, SemIR::LocId(query_impl.latest_decl_id),
  131. context.constant_values().Get(query_impl.self_id),
  132. query_impl.interface, final_impl.impl_id)) {
  133. CARBON_DIAGNOSTIC(ImplFinalOverlapsNonFinal, Error,
  134. "`impl` will never be used");
  135. auto builder = context.emitter().Build(query_impl.latest_decl_id,
  136. ImplFinalOverlapsNonFinal);
  137. CARBON_DIAGNOSTIC(
  138. ImplFinalOverlapsNonFinalNote, Note,
  139. "`final impl` declared here would always be used instead");
  140. builder.Note(final_impl.latest_decl_id, ImplFinalOverlapsNonFinalNote);
  141. builder.Emit();
  142. return true;
  143. }
  144. return false;
  145. };
  146. CARBON_CHECK(impl_a.is_final || impl_b.is_final);
  147. if (impl_b.is_final) {
  148. return diagnose_unmatchable_impl(impl_a, impl_b);
  149. } else {
  150. return diagnose_unmatchable_impl(impl_b, impl_a);
  151. }
  152. }
  153. // Final impls that overlap in their type structure must be in the
  154. // same file.
  155. //
  156. // Returns true if an error was diagnosed.
  157. static auto DiagnoseFinalImplsOverlapInDifferentFiles(Context& context,
  158. const ImplInfo& impl_a,
  159. const ImplInfo& impl_b)
  160. -> bool {
  161. if (impl_a.ir_id != impl_b.ir_id) {
  162. CARBON_DIAGNOSTIC(
  163. FinalImplOverlapsDifferentFile, Error,
  164. "`final impl` overlaps with `final impl` from another file");
  165. CARBON_DIAGNOSTIC(FinalImplOverlapsDifferentFileNote, Note,
  166. "imported `final impl` here");
  167. if (impl_a.is_local) {
  168. auto builder = context.emitter().Build(impl_a.latest_decl_id,
  169. FinalImplOverlapsDifferentFile);
  170. builder.Note(impl_b.latest_decl_id, FinalImplOverlapsDifferentFileNote);
  171. builder.Emit();
  172. } else {
  173. auto builder = context.emitter().Build(impl_b.latest_decl_id,
  174. FinalImplOverlapsDifferentFile);
  175. builder.Note(impl_a.latest_decl_id, FinalImplOverlapsDifferentFileNote);
  176. builder.Emit();
  177. }
  178. return true;
  179. }
  180. return false;
  181. }
  182. // Two final impls in the same file can not overlap in their type
  183. // structure if they are not in the same match_first block.
  184. //
  185. // TODO: Support for match_first needed here when they exist in the
  186. // toolchain.
  187. //
  188. // Returns true if an error was diagnosed.
  189. static auto DiagnoseFinalImplsOverlapOutsideMatchFirst(Context& context,
  190. const ImplInfo& impl_a,
  191. const ImplInfo& impl_b)
  192. -> bool {
  193. if (impl_a.is_local && impl_b.is_local) {
  194. CARBON_DIAGNOSTIC(FinalImplOverlapsSameFile, Error,
  195. "`final impl` overlaps with `final impl` from same file "
  196. "outside a `match_first` block");
  197. auto builder = context.emitter().Build(impl_b.latest_decl_id,
  198. FinalImplOverlapsSameFile);
  199. CARBON_DIAGNOSTIC(FinalImplOverlapsSameFileNote, Note,
  200. "other `final impl` here");
  201. builder.Note(impl_a.latest_decl_id, FinalImplOverlapsSameFileNote);
  202. builder.Emit();
  203. return true;
  204. }
  205. return false;
  206. }
  207. static auto ValidateImplsForInterface(Context& context,
  208. llvm::ArrayRef<ImplInfo> impls) -> void {
  209. // All `impl`s we look at here have the same `InterfaceId` (though different
  210. // `SpecificId`s in their `SpecificInterface`s). So we can grab the
  211. // `ImportIRId` for the interface a single time up front.
  212. auto interface_decl_id = context.interfaces()
  213. .Get(impls[0].interface.interface_id)
  214. .first_owning_decl_id;
  215. auto interface_ir_id = GetIRId(context, interface_decl_id);
  216. for (const auto& impl : impls) {
  217. if (impl.is_final && impl.is_local) {
  218. // =======================================================================
  219. /// Rules for an individual final impl.
  220. // =======================================================================
  221. DiagnoseFinalImplNotInSameFileAsRootSelfTypeOrInterface(context, impl,
  222. interface_ir_id);
  223. }
  224. }
  225. // TODO: We should revisit this and look for a way to do these checks in less
  226. // than quadratic time. From @zygoloid: Possibly by converting the set of
  227. // impls into a decision tree.
  228. //
  229. // For each impl, we compare it pair-wise which each impl found before it, so
  230. // that diagnostics are attached to the later impl, as the earlier impl on its
  231. // own does not generate a diagnostic.
  232. size_t num_impls = impls.size();
  233. for (auto [split_point, impl_b] : llvm::drop_begin(llvm::enumerate(impls))) {
  234. // Prevent diagnosing the same error multiple times for the same `impl_b`
  235. // against different impls before it. But still ensure we do give one of
  236. // each diagnostic when they are different errors.
  237. bool did_diagnose_non_final_impls_with_same_type_structure = false;
  238. bool did_diagnose_unmatchable_non_final_impl_with_final_impl = false;
  239. bool did_diagnose_final_impls_overlap_in_different_files = false;
  240. bool did_diagnose_final_impls_overlap_outside_match_first = false;
  241. auto impls_before = llvm::drop_end(impls, num_impls - split_point);
  242. for (const auto& impl_a : impls_before) {
  243. // Only enforce rules when at least one of the impls was written in this
  244. // file.
  245. if (!impl_a.is_local && !impl_b.is_local) {
  246. continue;
  247. }
  248. if (!impl_a.is_final && !impl_b.is_final) {
  249. // =====================================================================
  250. // Rules between two non-final impls.
  251. // =====================================================================
  252. if (!did_diagnose_non_final_impls_with_same_type_structure) {
  253. // Two impls in separate files will need to have some different
  254. // concrete element in their type structure, as enforced by the orphan
  255. // rule. So we don't need to check against non-local impls.
  256. if (impl_a.is_local && impl_b.is_local) {
  257. if (DiagnoseNonFinalImplsWithSameTypeStructure(context, impl_a,
  258. impl_b)) {
  259. // The same final `impl_a` may overlap with multiple `impl_b`s,
  260. // and we want to diagnose each `impl_b`.
  261. did_diagnose_non_final_impls_with_same_type_structure = true;
  262. }
  263. }
  264. }
  265. } else if (!impl_a.is_final || !impl_b.is_final) {
  266. // =====================================================================
  267. // Rules between final impl and non-final impl.
  268. // =====================================================================
  269. if (!did_diagnose_unmatchable_non_final_impl_with_final_impl) {
  270. if (DiagnoseUnmatchableNonFinalImplWithFinalImpl(context, impl_a,
  271. impl_b)) {
  272. did_diagnose_unmatchable_non_final_impl_with_final_impl = true;
  273. }
  274. }
  275. } else if (impl_a.type_structure.CompareStructure(
  276. TypeStructure::CompareTest::HasOverlap,
  277. impl_b.type_structure)) {
  278. // =====================================================================
  279. // Rules between two overlapping final impls.
  280. // =====================================================================
  281. CARBON_CHECK(impl_a.is_final && impl_b.is_final);
  282. if (!did_diagnose_final_impls_overlap_in_different_files) {
  283. if (DiagnoseFinalImplsOverlapInDifferentFiles(context, impl_a,
  284. impl_b)) {
  285. did_diagnose_final_impls_overlap_in_different_files = true;
  286. }
  287. }
  288. if (!did_diagnose_final_impls_overlap_outside_match_first) {
  289. if (DiagnoseFinalImplsOverlapOutsideMatchFirst(context, impl_a,
  290. impl_b)) {
  291. did_diagnose_final_impls_overlap_outside_match_first = true;
  292. }
  293. }
  294. }
  295. }
  296. }
  297. }
  298. // For each `impl` seen in this file, ensure that we import every available
  299. // `final impl` for the same interface, so that we can to check for
  300. // diagnostics about the relationship between them and the `impl`s in this
  301. // file.
  302. static auto ImportFinalImplsWithImplInFile(Context& context) -> void {
  303. struct InterfaceToImport {
  304. SemIR::ImportIRId ir_id;
  305. SemIR::InterfaceId interface_id;
  306. constexpr auto operator==(const InterfaceToImport& rhs) const
  307. -> bool = default;
  308. constexpr auto operator<=>(const InterfaceToImport& rhs) const -> auto {
  309. if (ir_id != rhs.ir_id) {
  310. return ir_id.index <=> rhs.ir_id.index;
  311. }
  312. return interface_id.index <=> rhs.interface_id.index;
  313. }
  314. };
  315. llvm::SmallVector<InterfaceToImport> interfaces_to_import;
  316. for (const auto& impl : context.impls().values()) {
  317. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  318. continue;
  319. }
  320. auto impl_import_ir_id = GetIRId(context, impl.first_owning_decl_id);
  321. if (impl_import_ir_id.has_value()) {
  322. // Only import `impl`s of interfaces for which there is a local `impl` of
  323. // that that interface.
  324. continue;
  325. }
  326. auto interface_id = impl.interface.interface_id;
  327. const auto& interface = context.interfaces().Get(interface_id);
  328. auto import_ir_id = GetIRId(context, interface.first_owning_decl_id);
  329. if (!import_ir_id.has_value()) {
  330. continue;
  331. }
  332. interfaces_to_import.push_back(
  333. {.ir_id = import_ir_id, .interface_id = interface_id});
  334. }
  335. llvm::sort(interfaces_to_import);
  336. llvm::unique(interfaces_to_import);
  337. struct ImplToImport {
  338. SemIR::ImportIRId ir_id;
  339. SemIR::ImplId import_impl_id;
  340. constexpr auto operator==(const ImplToImport& rhs) const -> bool = default;
  341. constexpr auto operator<=>(const ImplToImport& rhs) const -> auto {
  342. if (ir_id != rhs.ir_id) {
  343. return ir_id.index <=> rhs.ir_id.index;
  344. }
  345. return import_impl_id.index <=> rhs.import_impl_id.index;
  346. }
  347. };
  348. llvm::SmallVector<ImplToImport> impls_to_import;
  349. for (auto [ir_id, interface_id] : interfaces_to_import) {
  350. const SemIR::File& sem_ir = *context.import_irs().Get(ir_id).sem_ir;
  351. for (auto [impl_id, impl] : sem_ir.impls().enumerate()) {
  352. if (impl.is_final && impl.interface.interface_id == interface_id) {
  353. impls_to_import.push_back({.ir_id = ir_id, .import_impl_id = impl_id});
  354. }
  355. }
  356. }
  357. llvm::sort(impls_to_import);
  358. llvm::unique(impls_to_import);
  359. for (auto [ir_id, import_impl_id] : impls_to_import) {
  360. ImportImpl(context, ir_id, import_impl_id);
  361. }
  362. }
  363. auto ValidateImplsInFile(Context& context) -> void {
  364. ImportFinalImplsWithImplInFile(context);
  365. // Collect all of the impls sorted into contiguous segments by their
  366. // interface. We only need to compare impls within each such segment. We don't
  367. // keep impls with an Error in them, as they may be missing other values
  368. // needed to check the diagnostics and they already have a diagnostic printed
  369. // about them anyhow. We also verify the impl has an `InterfaceId` since it
  370. // can be missing, in which case a diagnostic would have been generated
  371. // already as well.
  372. llvm::SmallVector<ImplInfo> impl_ids_by_interface(llvm::map_range(
  373. llvm::make_filter_range(
  374. context.impls().enumerate(),
  375. [](std::pair<SemIR::ImplId, const SemIR::Impl&> pair) {
  376. return pair.second.witness_id != SemIR::ErrorInst::InstId &&
  377. pair.second.interface.interface_id.has_value();
  378. }),
  379. [&](std::pair<SemIR::ImplId, const SemIR::Impl&> pair) {
  380. return GetImplInfo(context, pair.first);
  381. }));
  382. llvm::stable_sort(impl_ids_by_interface, [](const ImplInfo& lhs,
  383. const ImplInfo& rhs) {
  384. return lhs.interface.interface_id.index < rhs.interface.interface_id.index;
  385. });
  386. const auto* it = impl_ids_by_interface.begin();
  387. while (it != impl_ids_by_interface.end()) {
  388. const auto* segment_begin = it;
  389. auto begin_interface_id = segment_begin->interface.interface_id;
  390. do {
  391. ++it;
  392. } while (it != impl_ids_by_interface.end() &&
  393. it->interface.interface_id == begin_interface_id);
  394. const auto* segment_end = it;
  395. ValidateImplsForInterface(context, {segment_begin, segment_end});
  396. }
  397. }
  398. } // namespace Carbon::Check