deduce.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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/deduce.h"
  5. #include "toolchain/base/kind_switch.h"
  6. #include "toolchain/check/context.h"
  7. #include "toolchain/check/convert.h"
  8. #include "toolchain/check/generic.h"
  9. #include "toolchain/check/subst.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/impl.h"
  12. #include "toolchain/sem_ir/typed_insts.h"
  13. namespace Carbon::Check {
  14. namespace {
  15. // A list of pairs of (instruction from generic, corresponding instruction from
  16. // call to of generic) for which we still need to perform deduction, along with
  17. // methods to add and pop pending deductions from the list. Deductions are
  18. // popped in order from most- to least-recently pushed, with the intent that
  19. // they are visited in depth-first order, although the order is not expected to
  20. // matter except when it influences which error is diagnosed.
  21. class DeductionWorklist {
  22. public:
  23. explicit DeductionWorklist(Context& context) : context_(context) {}
  24. struct PendingDeduction {
  25. SemIR::InstId param;
  26. SemIR::InstId arg;
  27. bool needs_substitution;
  28. };
  29. // Adds a single (param, arg) deduction.
  30. auto Add(SemIR::InstId param, SemIR::InstId arg, bool needs_substitution)
  31. -> void {
  32. deductions_.push_back(
  33. {.param = param, .arg = arg, .needs_substitution = needs_substitution});
  34. }
  35. // Adds a list of (param, arg) deductions. These are added in reverse order so
  36. // they are popped in forward order.
  37. auto AddAll(llvm::ArrayRef<SemIR::InstId> params,
  38. llvm::ArrayRef<SemIR::InstId> args, bool needs_substitution)
  39. -> void {
  40. if (params.size() != args.size()) {
  41. // TODO: Decide whether to error on this or just treat the parameter list
  42. // as non-deduced. For now we treat it as non-deduced.
  43. return;
  44. }
  45. for (auto [param, arg] : llvm::reverse(llvm::zip_equal(params, args))) {
  46. Add(param, arg, needs_substitution);
  47. }
  48. }
  49. auto AddAll(SemIR::InstBlockId params, llvm::ArrayRef<SemIR::InstId> args,
  50. bool needs_substitution) -> void {
  51. AddAll(context_.inst_blocks().Get(params), args, needs_substitution);
  52. }
  53. auto AddAll(SemIR::InstBlockId params, SemIR::InstBlockId args,
  54. bool needs_substitution) -> void {
  55. AddAll(context_.inst_blocks().Get(params), context_.inst_blocks().Get(args),
  56. needs_substitution);
  57. }
  58. // Returns whether we have completed all deductions.
  59. auto Done() -> bool { return deductions_.empty(); }
  60. // Pops the next deduction. Requires `!Done()`.
  61. auto PopNext() -> PendingDeduction { return deductions_.pop_back_val(); }
  62. private:
  63. Context& context_;
  64. llvm::SmallVector<PendingDeduction> deductions_;
  65. };
  66. } // namespace
  67. static auto NoteGenericHere(Context& context, SemIR::GenericId generic_id,
  68. Context::DiagnosticBuilder& diag) -> void {
  69. CARBON_DIAGNOSTIC(DeductionGenericHere, Note,
  70. "while deducing parameters of generic declared here");
  71. diag.Note(context.generics().Get(generic_id).decl_id, DeductionGenericHere);
  72. }
  73. auto DeduceGenericCallArguments(
  74. Context& context, SemIR::LocId loc_id, SemIR::GenericId generic_id,
  75. SemIR::SpecificId enclosing_specific_id,
  76. [[maybe_unused]] SemIR::InstBlockId implicit_params_id,
  77. SemIR::InstBlockId params_id, [[maybe_unused]] SemIR::InstId self_id,
  78. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::SpecificId {
  79. DeductionWorklist worklist(context);
  80. llvm::SmallVector<SemIR::InstId> result_arg_ids;
  81. llvm::SmallVector<Substitution> substitutions;
  82. // Copy any outer generic arguments from the specified instance and prepare to
  83. // substitute them into the function declaration.
  84. if (enclosing_specific_id.is_valid()) {
  85. auto args = context.inst_blocks().Get(
  86. context.specifics().Get(enclosing_specific_id).args_id);
  87. result_arg_ids.assign(args.begin(), args.end());
  88. // TODO: Subst is linear in the length of the substitutions list. Change it
  89. // so we can pass in an array mapping indexes to substitutions instead.
  90. substitutions.reserve(args.size());
  91. for (auto [i, subst_inst_id] : llvm::enumerate(args)) {
  92. substitutions.push_back(
  93. {.bind_id = SemIR::CompileTimeBindIndex(i),
  94. .replacement_id = context.constant_values().Get(subst_inst_id)});
  95. }
  96. }
  97. auto first_deduced_index = SemIR::CompileTimeBindIndex(result_arg_ids.size());
  98. // Initialize the deduced arguments to Invalid.
  99. result_arg_ids.resize(context.inst_blocks()
  100. .Get(context.generics().Get(generic_id).bindings_id)
  101. .size(),
  102. SemIR::InstId::Invalid);
  103. // Prepare to perform deduction of the explicit parameters against their
  104. // arguments.
  105. // TODO: Also perform deduction for type of self.
  106. worklist.AddAll(params_id, arg_ids, /*needs_substitution=*/true);
  107. while (!worklist.Done()) {
  108. auto [param_id, arg_id, needs_substitution] = worklist.PopNext();
  109. // If the parameter has a symbolic type, deduce against that.
  110. auto param_type_id = context.insts().Get(param_id).type_id();
  111. if (param_type_id.AsConstantId().is_symbolic()) {
  112. worklist.Add(
  113. context.types().GetInstId(param_type_id),
  114. context.types().GetInstId(context.insts().Get(arg_id).type_id()),
  115. needs_substitution);
  116. } else {
  117. // The argument needs to have the same type as the parameter.
  118. DiagnosticAnnotationScope annotate_diagnostics(
  119. &context.emitter(), [&](auto& builder) {
  120. if (auto param = context.insts().TryGetAs<SemIR::BindSymbolicName>(
  121. param_id)) {
  122. CARBON_DIAGNOSTIC(
  123. InitializingGenericParam, Note,
  124. "initializing generic parameter `{0}` declared here",
  125. SemIR::NameId);
  126. builder.Note(
  127. param_id, InitializingGenericParam,
  128. context.entity_names().Get(param->entity_name_id).name_id);
  129. }
  130. });
  131. arg_id = ConvertToValueOfType(context, loc_id, arg_id, param_type_id);
  132. if (arg_id == SemIR::InstId::BuiltinError) {
  133. return SemIR::SpecificId::Invalid;
  134. }
  135. }
  136. // If the parameter is a symbolic constant, deduce against it.
  137. auto param_const_id = context.constant_values().Get(param_id);
  138. if (!param_const_id.is_valid() || !param_const_id.is_symbolic()) {
  139. continue;
  140. }
  141. // If we've not yet substituted into the parameter, do so now.
  142. if (needs_substitution) {
  143. param_const_id = SubstConstant(context, param_const_id, substitutions);
  144. if (!param_const_id.is_valid() || !param_const_id.is_symbolic()) {
  145. continue;
  146. }
  147. needs_substitution = false;
  148. }
  149. CARBON_KIND_SWITCH(context.insts().Get(context.constant_values().GetInstId(
  150. param_const_id))) {
  151. // Deducing a symbolic binding from an argument with a constant value
  152. // deduces the binding as having that constant value.
  153. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  154. auto& entity_name = context.entity_names().Get(bind.entity_name_id);
  155. auto index = entity_name.bind_index;
  156. if (index.is_valid() && index >= first_deduced_index) {
  157. CARBON_CHECK(static_cast<size_t>(index.index) < result_arg_ids.size(),
  158. "Deduced value for unexpected index {0}; expected to "
  159. "deduce {1} arguments.",
  160. index, result_arg_ids.size());
  161. auto arg_const_inst_id =
  162. context.constant_values().GetConstantInstId(arg_id);
  163. if (arg_const_inst_id.is_valid()) {
  164. if (result_arg_ids[index.index].is_valid() &&
  165. result_arg_ids[index.index] != arg_const_inst_id) {
  166. // TODO: Include the two different deduced values.
  167. CARBON_DIAGNOSTIC(DeductionInconsistent, Error,
  168. "inconsistent deductions for value of generic "
  169. "parameter `{0}`",
  170. SemIR::NameId);
  171. auto diag = context.emitter().Build(loc_id, DeductionInconsistent,
  172. entity_name.name_id);
  173. NoteGenericHere(context, generic_id, diag);
  174. diag.Emit();
  175. return SemIR::SpecificId::Invalid;
  176. }
  177. result_arg_ids[index.index] = arg_const_inst_id;
  178. }
  179. }
  180. break;
  181. }
  182. // TODO: Handle more cases.
  183. default:
  184. break;
  185. }
  186. }
  187. // Check we deduced an argument value for every parameter.
  188. for (auto [i, deduced_arg_id] :
  189. llvm::enumerate(llvm::ArrayRef(result_arg_ids)
  190. .drop_front(first_deduced_index.index))) {
  191. if (!deduced_arg_id.is_valid()) {
  192. auto binding_index = first_deduced_index.index + i;
  193. auto binding_id = context.inst_blocks().Get(
  194. context.generics().Get(generic_id).bindings_id)[binding_index];
  195. auto entity_name_id =
  196. context.insts().GetAs<SemIR::AnyBindName>(binding_id).entity_name_id;
  197. CARBON_DIAGNOSTIC(DeductionIncomplete, Error,
  198. "cannot deduce value for generic parameter `{0}`",
  199. SemIR::NameId);
  200. auto diag = context.emitter().Build(
  201. loc_id, DeductionIncomplete,
  202. context.entity_names().Get(entity_name_id).name_id);
  203. NoteGenericHere(context, generic_id, diag);
  204. diag.Emit();
  205. return SemIR::SpecificId::Invalid;
  206. }
  207. }
  208. // TODO: Convert the deduced values to the types of the bindings.
  209. return MakeSpecific(context, generic_id,
  210. context.inst_blocks().AddCanonical(result_arg_ids));
  211. }
  212. // Deduces the impl arguments to use in a use of a parameterized impl. Returns
  213. // `Invalid` if deduction fails.
  214. auto DeduceImplArguments(Context& context, const SemIR::Impl& impl,
  215. SemIR::ConstantId self_id,
  216. SemIR::ConstantId constraint_id) -> SemIR::SpecificId {
  217. CARBON_CHECK(impl.generic_id.is_valid(),
  218. "Performing deduction for non-generic impl");
  219. // TODO: This is a placeholder. Implement deduction.
  220. static_cast<void>(context);
  221. static_cast<void>(self_id);
  222. static_cast<void>(constraint_id);
  223. return SemIR::SpecificId::Invalid;
  224. }
  225. } // namespace Carbon::Check