impl_validation.cpp 18 KB

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