impl_validation.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. std::optional<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. static 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. // Don't diagnose structures that contain errors.
  245. if (!impl_a.type_structure || !impl_b.type_structure) {
  246. continue;
  247. }
  248. // Only enforce rules when at least one of the impls was written in this
  249. // file.
  250. if (!impl_a.is_local && !impl_b.is_local) {
  251. continue;
  252. }
  253. if (!impl_a.is_final && !impl_b.is_final) {
  254. // =====================================================================
  255. // Rules between two non-final impls.
  256. // =====================================================================
  257. if (!did_diagnose_non_final_impls_with_same_type_structure) {
  258. // Two impls in separate files will need to have some different
  259. // concrete element in their type structure, as enforced by the orphan
  260. // rule. So we don't need to check against non-local impls.
  261. if (impl_a.is_local && impl_b.is_local) {
  262. if (DiagnoseNonFinalImplsWithSameTypeStructure(context, impl_a,
  263. impl_b)) {
  264. // The same final `impl_a` may overlap with multiple `impl_b`s,
  265. // and we want to diagnose each `impl_b`.
  266. did_diagnose_non_final_impls_with_same_type_structure = true;
  267. }
  268. }
  269. }
  270. } else if (!impl_a.is_final || !impl_b.is_final) {
  271. // =====================================================================
  272. // Rules between final impl and non-final impl.
  273. // =====================================================================
  274. if (!did_diagnose_unmatchable_non_final_impl_with_final_impl) {
  275. if (DiagnoseUnmatchableNonFinalImplWithFinalImpl(context, impl_a,
  276. impl_b)) {
  277. did_diagnose_unmatchable_non_final_impl_with_final_impl = true;
  278. }
  279. }
  280. } else if (impl_a.type_structure->CompareStructure(
  281. TypeStructure::CompareTest::HasOverlap,
  282. *impl_b.type_structure)) {
  283. // =====================================================================
  284. // Rules between two overlapping final impls.
  285. // =====================================================================
  286. CARBON_CHECK(impl_a.is_final && impl_b.is_final);
  287. if (!did_diagnose_final_impls_overlap_in_different_files) {
  288. if (DiagnoseFinalImplsOverlapInDifferentFiles(context, impl_a,
  289. impl_b)) {
  290. did_diagnose_final_impls_overlap_in_different_files = true;
  291. }
  292. }
  293. if (!did_diagnose_final_impls_overlap_outside_match_first) {
  294. if (DiagnoseFinalImplsOverlapOutsideMatchFirst(context, impl_a,
  295. impl_b)) {
  296. did_diagnose_final_impls_overlap_outside_match_first = true;
  297. }
  298. }
  299. }
  300. }
  301. }
  302. }
  303. // For each `impl` seen in this file, ensure that we import every available
  304. // `final impl` for the same interface, so that we can to check for
  305. // diagnostics about the relationship between them and the `impl`s in this
  306. // file.
  307. static auto ImportFinalImplsWithImplInFile(Context& context) -> void {
  308. struct InterfaceToImport {
  309. SemIR::ImportIRId ir_id;
  310. SemIR::InterfaceId interface_id;
  311. constexpr auto operator==(const InterfaceToImport& rhs) const
  312. -> bool = default;
  313. constexpr auto operator<=>(const InterfaceToImport& rhs) const -> auto {
  314. if (ir_id != rhs.ir_id) {
  315. return ir_id.index <=> rhs.ir_id.index;
  316. }
  317. return interface_id.index <=> rhs.interface_id.index;
  318. }
  319. };
  320. llvm::SmallVector<InterfaceToImport> interfaces_to_import;
  321. for (const auto& impl : context.impls().values()) {
  322. if (impl.witness_id == SemIR::ErrorInst::InstId) {
  323. continue;
  324. }
  325. auto impl_import_ir_id = GetIRId(context, impl.first_owning_decl_id);
  326. if (impl_import_ir_id.has_value()) {
  327. // Only import `impl`s of interfaces for which there is a local `impl` of
  328. // that that interface.
  329. continue;
  330. }
  331. auto interface_id = impl.interface.interface_id;
  332. const auto& interface = context.interfaces().Get(interface_id);
  333. if (!interface.first_owning_decl_id.has_value()) {
  334. continue;
  335. }
  336. const auto& import_ir_inst =
  337. GetCanonicalImportIRInst(context, interface.first_owning_decl_id);
  338. if (!import_ir_inst.ir_id().has_value()) {
  339. continue;
  340. }
  341. interfaces_to_import.push_back(
  342. {.ir_id = import_ir_inst.ir_id(),
  343. .interface_id =
  344. context.import_irs()
  345. .Get(import_ir_inst.ir_id())
  346. .sem_ir->insts()
  347. .GetAs<SemIR::InterfaceDecl>(import_ir_inst.inst_id())
  348. .interface_id});
  349. }
  350. llvm::sort(interfaces_to_import);
  351. llvm::unique(interfaces_to_import);
  352. struct ImplToImport {
  353. SemIR::ImportIRId ir_id;
  354. SemIR::ImplId import_impl_id;
  355. constexpr auto operator==(const ImplToImport& rhs) const -> bool = default;
  356. constexpr auto operator<=>(const ImplToImport& rhs) const -> auto {
  357. if (ir_id != rhs.ir_id) {
  358. return ir_id.index <=> rhs.ir_id.index;
  359. }
  360. return import_impl_id.index <=> rhs.import_impl_id.index;
  361. }
  362. };
  363. llvm::SmallVector<ImplToImport> impls_to_import;
  364. for (auto [ir_id, interface_id] : interfaces_to_import) {
  365. const SemIR::File& sem_ir = *context.import_irs().Get(ir_id).sem_ir;
  366. for (auto [impl_id, impl] : sem_ir.impls().enumerate()) {
  367. if (impl.is_final && impl.interface.interface_id == interface_id) {
  368. impls_to_import.push_back({.ir_id = ir_id, .import_impl_id = impl_id});
  369. }
  370. }
  371. }
  372. llvm::sort(impls_to_import);
  373. llvm::unique(impls_to_import);
  374. for (auto [ir_id, import_impl_id] : impls_to_import) {
  375. ImportImpl(context, ir_id, import_impl_id);
  376. }
  377. }
  378. auto ValidateImplsInFile(Context& context) -> void {
  379. ImportFinalImplsWithImplInFile(context);
  380. // Collect all of the impls sorted into contiguous segments by their
  381. // interface. We only need to compare impls within each such segment. We don't
  382. // keep impls with an Error in them, as they may be missing other values
  383. // needed to check the diagnostics and they already have a diagnostic printed
  384. // about them anyhow. We also verify the impl has an `InterfaceId` since it
  385. // can be missing, in which case a diagnostic would have been generated
  386. // already as well.
  387. llvm::SmallVector<ImplInfo> impl_ids_by_interface(llvm::map_range(
  388. llvm::make_filter_range(
  389. context.impls().enumerate(),
  390. [](std::pair<SemIR::ImplId, const SemIR::Impl&> pair) {
  391. return pair.second.witness_id != SemIR::ErrorInst::InstId &&
  392. pair.second.interface.interface_id.has_value();
  393. }),
  394. [&](std::pair<SemIR::ImplId, const SemIR::Impl&> pair) {
  395. return GetImplInfo(context, pair.first);
  396. }));
  397. llvm::stable_sort(impl_ids_by_interface, [](const ImplInfo& lhs,
  398. const ImplInfo& rhs) {
  399. return lhs.interface.interface_id.index < rhs.interface.interface_id.index;
  400. });
  401. const auto* it = impl_ids_by_interface.begin();
  402. while (it != impl_ids_by_interface.end()) {
  403. const auto* segment_begin = it;
  404. auto begin_interface_id = segment_begin->interface.interface_id;
  405. do {
  406. ++it;
  407. } while (it != impl_ids_by_interface.end() &&
  408. it->interface.interface_id == begin_interface_id);
  409. const auto* segment_end = it;
  410. ValidateImplsForInterface(context, {segment_begin, segment_end});
  411. }
  412. }
  413. } // namespace Carbon::Check