deduce.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 "llvm/ADT/SmallBitVector.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/generic.h"
  10. #include "toolchain/check/subst.h"
  11. #include "toolchain/diagnostics/diagnostic.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/impl.h"
  14. #include "toolchain/sem_ir/type.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Check {
  17. namespace {
  18. // A list of pairs of (instruction from generic, corresponding instruction from
  19. // call to of generic) for which we still need to perform deduction, along with
  20. // methods to add and pop pending deductions from the list. Deductions are
  21. // popped in order from most- to least-recently pushed, with the intent that
  22. // they are visited in depth-first order, although the order is not expected to
  23. // matter except when it influences which error is diagnosed.
  24. class DeductionWorklist {
  25. public:
  26. // `context` must not be null.
  27. explicit DeductionWorklist(Context* context) : context_(context) {}
  28. struct PendingDeduction {
  29. SemIR::InstId param;
  30. SemIR::InstId arg;
  31. };
  32. // Adds a single (param, arg) deduction.
  33. auto Add(SemIR::InstId param, SemIR::InstId arg) -> void {
  34. deductions_.push_back({.param = param, .arg = arg});
  35. }
  36. // Adds a single (param, arg) type deduction.
  37. auto Add(SemIR::TypeId param, SemIR::TypeId arg) -> void {
  38. Add(context_->types().GetInstId(param), context_->types().GetInstId(arg));
  39. }
  40. // Adds a single (param, arg) deduction of a specific.
  41. auto Add(SemIR::SpecificId param, SemIR::SpecificId arg) -> void {
  42. if (!param.has_value() || !arg.has_value()) {
  43. return;
  44. }
  45. auto& param_specific = context_->specifics().Get(param);
  46. auto& arg_specific = context_->specifics().Get(arg);
  47. if (param_specific.generic_id != arg_specific.generic_id) {
  48. // TODO: Decide whether to error on this or just treat the specific as
  49. // non-deduced. For now we treat it as non-deduced.
  50. return;
  51. }
  52. AddAll(param_specific.args_id, arg_specific.args_id);
  53. }
  54. // Adds a list of (param, arg) deductions. These are added in reverse order so
  55. // they are popped in forward order.
  56. template <typename ElementId>
  57. auto AddAll(llvm::ArrayRef<ElementId> params, llvm::ArrayRef<ElementId> args)
  58. -> void {
  59. if (params.size() != args.size()) {
  60. // TODO: Decide whether to error on this or just treat the parameter list
  61. // as non-deduced. For now we treat it as non-deduced.
  62. return;
  63. }
  64. for (auto [param, arg] : llvm::reverse(llvm::zip_equal(params, args))) {
  65. Add(param, arg);
  66. }
  67. }
  68. auto AddAll(SemIR::InstBlockId params, llvm::ArrayRef<SemIR::InstId> args)
  69. -> void {
  70. AddAll(context_->inst_blocks().Get(params), args);
  71. }
  72. auto AddAll(SemIR::StructTypeFieldsId params, SemIR::StructTypeFieldsId args)
  73. -> void {
  74. const auto& param_fields = context_->struct_type_fields().Get(params);
  75. const auto& arg_fields = context_->struct_type_fields().Get(args);
  76. if (param_fields.size() != arg_fields.size()) {
  77. // TODO: Decide whether to error on this or just treat the parameter list
  78. // as non-deduced. For now we treat it as non-deduced.
  79. return;
  80. }
  81. // Don't do deduction unless the names match in order.
  82. // TODO: Support reordering of names.
  83. for (auto [param, arg] : llvm::zip_equal(param_fields, arg_fields)) {
  84. if (param.name_id != arg.name_id) {
  85. return;
  86. }
  87. }
  88. for (auto [param, arg] :
  89. llvm::reverse(llvm::zip_equal(param_fields, arg_fields))) {
  90. Add(param.type_inst_id, arg.type_inst_id);
  91. }
  92. }
  93. auto AddAll(SemIR::InstBlockId params, SemIR::InstBlockId args) -> void {
  94. AddAll(context_->inst_blocks().Get(params),
  95. context_->inst_blocks().Get(args));
  96. }
  97. // Adds a (param, arg) pair for an instruction argument, given its kind.
  98. auto AddInstArg(SemIR::Inst::ArgAndKind param, int32_t arg) -> void {
  99. CARBON_KIND_SWITCH(param) {
  100. case SemIR::IdKind::None:
  101. case SemIR::IdKind::For<SemIR::ClassId>:
  102. case SemIR::IdKind::For<SemIR::IntKind>:
  103. // Decided on 2025-04-02 not to do deduction through facet types, because
  104. // types can implement a generic interface multiple times with different
  105. // arguments. See:
  106. // https://docs.google.com/document/d/1Iut5f2TQBrtBNIduF4vJYOKfw7MbS8xH_J01_Q4e6Rk/edit?pli=1&resourcekey=0-mc_vh5UzrzXfU4kO-3tOjA&tab=t.0#heading=h.95phmuvxog9n
  107. case SemIR::IdKind::For<SemIR::FacetTypeId>:
  108. break;
  109. case CARBON_KIND(SemIR::InstId inst_id): {
  110. Add(inst_id, SemIR::InstId(arg));
  111. break;
  112. }
  113. case CARBON_KIND(SemIR::TypeInstId inst_id): {
  114. Add(inst_id, SemIR::InstId(arg));
  115. break;
  116. }
  117. case CARBON_KIND(SemIR::StructTypeFieldsId fields_id): {
  118. AddAll(fields_id, SemIR::StructTypeFieldsId(arg));
  119. break;
  120. }
  121. case CARBON_KIND(SemIR::InstBlockId inst_block_id): {
  122. AddAll(inst_block_id, SemIR::InstBlockId(arg));
  123. break;
  124. }
  125. case CARBON_KIND(SemIR::SpecificId specific_id): {
  126. Add(specific_id, SemIR::SpecificId(arg));
  127. break;
  128. }
  129. default:
  130. CARBON_FATAL("unexpected argument kind");
  131. }
  132. }
  133. // Returns whether we have completed all deductions.
  134. auto Done() -> bool { return deductions_.empty(); }
  135. // Pops the next deduction. Requires `!Done()`.
  136. auto PopNext() -> PendingDeduction { return deductions_.pop_back_val(); }
  137. private:
  138. Context* context_;
  139. llvm::SmallVector<PendingDeduction> deductions_;
  140. };
  141. // State that is tracked throughout the deduction process.
  142. class DeductionContext {
  143. public:
  144. // Preparse to perform deduction. If an enclosing specific or self type
  145. // are provided, adds the corresponding arguments as known arguments that will
  146. // not be deduced. `context` must not be null.
  147. DeductionContext(Context* context, SemIR::LocId loc_id,
  148. SemIR::GenericId generic_id,
  149. SemIR::SpecificId enclosing_specific_id,
  150. SemIR::InstId self_type_id, bool diagnose);
  151. auto context() const -> Context& { return *context_; }
  152. // Adds a pending deduction of `param` from `arg`. `needs_substitution`
  153. // indicates whether we need to substitute known generic parameters into
  154. // `param`.
  155. template <typename ParamT, typename ArgT>
  156. auto Add(ParamT param, ArgT arg) -> void {
  157. worklist_.Add(param, arg);
  158. }
  159. // Same as `Add` but for an array or block of operands.
  160. template <typename ParamT, typename ArgT>
  161. auto AddAll(ParamT param, ArgT arg) -> void {
  162. worklist_.AddAll(param, arg);
  163. }
  164. // Performs all deductions in the deduction worklist. Returns whether
  165. // deduction succeeded.
  166. auto Deduce() -> bool;
  167. // Returns whether every generic parameter has a corresponding deduced generic
  168. // argument. If not, issues a suitable diagnostic.
  169. auto CheckDeductionIsComplete() -> bool;
  170. // Forms a specific corresponding to the deduced generic with the deduced
  171. // argument list. Must not be called before deduction is complete.
  172. auto MakeSpecific() -> SemIR::SpecificId;
  173. private:
  174. auto NoteInitializingParam(SemIR::InstId param_id, auto& builder) -> void {
  175. if (auto param = context().insts().TryGetAs<SemIR::SymbolicBindingPattern>(
  176. param_id)) {
  177. CARBON_DIAGNOSTIC(InitializingGenericParam, Note,
  178. "initializing generic parameter `{0}` declared here",
  179. SemIR::NameId);
  180. builder.Note(param_id, InitializingGenericParam,
  181. context().entity_names().Get(param->entity_name_id).name_id);
  182. } else {
  183. NoteGenericHere(context(), generic_id_, builder);
  184. }
  185. }
  186. Context* context_;
  187. SemIR::LocId loc_id_;
  188. SemIR::GenericId generic_id_;
  189. bool diagnose_;
  190. DeductionWorklist worklist_;
  191. llvm::SmallVector<SemIR::InstId> result_arg_ids_;
  192. llvm::SmallVector<Substitution> substitutions_;
  193. SemIR::CompileTimeBindIndex first_deduced_index_;
  194. // Non-deduced indexes, indexed by parameter index - first_deduced_index_.
  195. llvm::SmallBitVector non_deduced_indexes_;
  196. };
  197. } // namespace
  198. static auto NoteGenericHere(Context& context, SemIR::GenericId generic_id,
  199. DiagnosticBuilder& diag) -> void {
  200. CARBON_DIAGNOSTIC(DeductionGenericHere, Note,
  201. "while deducing parameters of generic declared here");
  202. diag.Note(context.generics().Get(generic_id).decl_id, DeductionGenericHere);
  203. }
  204. DeductionContext::DeductionContext(Context* context, SemIR::LocId loc_id,
  205. SemIR::GenericId generic_id,
  206. SemIR::SpecificId enclosing_specific_id,
  207. SemIR::InstId self_type_id, bool diagnose)
  208. : context_(context),
  209. loc_id_(loc_id),
  210. generic_id_(generic_id),
  211. diagnose_(diagnose),
  212. worklist_(context),
  213. first_deduced_index_(0) {
  214. CARBON_CHECK(generic_id.has_value(),
  215. "Performing deduction for non-generic entity");
  216. // Initialize the deduced arguments to `None`.
  217. result_arg_ids_.resize(
  218. context->inst_blocks()
  219. .Get(context->generics().Get(generic_id_).bindings_id)
  220. .size(),
  221. SemIR::InstId::None);
  222. if (enclosing_specific_id.has_value()) {
  223. // Copy any outer generic arguments from the specified instance and prepare
  224. // to substitute them into the function declaration.
  225. auto args = context->inst_blocks().Get(
  226. context->specifics().Get(enclosing_specific_id).args_id);
  227. llvm::copy(args, result_arg_ids_.begin());
  228. // TODO: Subst is linear in the length of the substitutions list. Change
  229. // it so we can pass in an array mapping indexes to substitutions instead.
  230. substitutions_.reserve(args.size() + result_arg_ids_.size());
  231. for (auto [i, subst_inst_id] : llvm::enumerate(args)) {
  232. substitutions_.push_back(
  233. {.bind_id = SemIR::CompileTimeBindIndex(i),
  234. .replacement_id = context->constant_values().Get(subst_inst_id)});
  235. }
  236. first_deduced_index_ = SemIR::CompileTimeBindIndex(args.size());
  237. }
  238. if (self_type_id.has_value()) {
  239. // Copy the provided `Self` type as the value of the next binding.
  240. auto self_index = first_deduced_index_;
  241. result_arg_ids_[self_index.index] = self_type_id;
  242. substitutions_.push_back(
  243. {.bind_id = SemIR::CompileTimeBindIndex(self_index),
  244. .replacement_id = context->constant_values().Get(self_type_id)});
  245. first_deduced_index_ = SemIR::CompileTimeBindIndex(self_index.index + 1);
  246. }
  247. non_deduced_indexes_.resize(result_arg_ids_.size() -
  248. first_deduced_index_.index);
  249. }
  250. auto DeductionContext::Deduce() -> bool {
  251. while (!worklist_.Done()) {
  252. auto [param_id, arg_id] = worklist_.PopNext();
  253. // TODO: Bail out if there's nothing to deduce: if we're not in a pattern
  254. // and the parameter doesn't have a symbolic constant value.
  255. auto param_type_id = context().insts().Get(param_id).type_id();
  256. if (context().types().Is<SemIR::PatternType>(param_type_id)) {
  257. param_type_id =
  258. SemIR::ExtractScrutineeType(context().sem_ir(), param_type_id);
  259. }
  260. // If the parameter has a symbolic type, deduce against that.
  261. if (param_type_id.is_symbolic()) {
  262. Add(context().types().GetInstId(param_type_id),
  263. context().types().GetInstId(context().insts().Get(arg_id).type_id()));
  264. } else {
  265. // The argument (e.g. a TupleLiteral of types) may be convertible to a
  266. // compile-time value (e.g. TupleType) that we can decompose further.
  267. // So we do this conversion here, even though we will later try convert
  268. // again when we have deduced all of the bindings.
  269. Diagnostics::AnnotationScope annotate_diagnostics(
  270. &context().emitter(), [&](auto& builder) {
  271. if (diagnose_) {
  272. NoteInitializingParam(param_id, builder);
  273. }
  274. });
  275. // TODO: The call logic should reuse the conversion here (if any) instead
  276. // of doing the same conversion again. At the moment we throw away the
  277. // converted arg_id.
  278. arg_id = diagnose_ ? ConvertToValueOfType(context(), loc_id_, arg_id,
  279. param_type_id)
  280. : TryConvertToValueOfType(context(), loc_id_, arg_id,
  281. param_type_id);
  282. if (arg_id == SemIR::ErrorInst::InstId) {
  283. return false;
  284. }
  285. }
  286. // Attempt to match `param_inst` against `arg_id`. If the match succeeds,
  287. // this should `continue` the outer loop. On `break`, we will try to desugar
  288. // the parameter to continue looking for a match.
  289. auto param_inst = context().insts().Get(param_id);
  290. CARBON_KIND_SWITCH(param_inst) {
  291. // Deducing a symbolic binding pattern from an argument deduces the
  292. // binding as having that constant value. For example, deducing
  293. // `(T:! type)` against `(i32)` deduces `T` to be `i32`. This only arises
  294. // when initializing a generic parameter from an explicitly specified
  295. // argument, and in this case, the argument is required to be a
  296. // compile-time constant.
  297. case CARBON_KIND(SemIR::SymbolicBindingPattern bind): {
  298. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  299. auto index = entity_name.bind_index();
  300. if (!index.has_value()) {
  301. break;
  302. }
  303. CARBON_CHECK(
  304. index >= first_deduced_index_ &&
  305. static_cast<size_t>(index.index) < result_arg_ids_.size(),
  306. "Unexpected index {0} for symbolic binding pattern; "
  307. "expected to be in range [{1}, {2})",
  308. index.index, first_deduced_index_.index, result_arg_ids_.size());
  309. CARBON_CHECK(!result_arg_ids_[index.index].has_value(),
  310. "Deduced a value for parameter prior to its declaration");
  311. auto arg_const_inst_id =
  312. context().constant_values().GetConstantInstId(arg_id);
  313. if (!arg_const_inst_id.has_value()) {
  314. if (diagnose_) {
  315. CARBON_DIAGNOSTIC(CompTimeArgumentNotConstant, Error,
  316. "argument for generic parameter is not a "
  317. "compile-time constant");
  318. auto diag =
  319. context().emitter().Build(loc_id_, CompTimeArgumentNotConstant);
  320. NoteInitializingParam(param_id, diag);
  321. diag.Emit();
  322. }
  323. return false;
  324. }
  325. result_arg_ids_[index.index] = arg_const_inst_id;
  326. // This parameter index should not be deduced if it appears later.
  327. non_deduced_indexes_[index.index - first_deduced_index_.index] = true;
  328. continue;
  329. }
  330. // Deducing a symbolic binding appearing within an expression against a
  331. // constant value deduces the binding as having that value. For example,
  332. // deducing `[T:! type](x: T)` against `("foo")` deduces `T` as `String`.
  333. case CARBON_KIND(SemIR::BindSymbolicName bind): {
  334. auto& entity_name = context().entity_names().Get(bind.entity_name_id);
  335. auto index = entity_name.bind_index();
  336. if (!index.has_value() || index < first_deduced_index_ ||
  337. non_deduced_indexes_[index.index - first_deduced_index_.index]) {
  338. break;
  339. }
  340. CARBON_CHECK(static_cast<size_t>(index.index) < result_arg_ids_.size(),
  341. "Deduced value for unexpected index {0}; expected to "
  342. "deduce {1} arguments.",
  343. index, result_arg_ids_.size());
  344. auto arg_const_inst_id =
  345. context().constant_values().GetConstantInstId(arg_id);
  346. if (arg_const_inst_id.has_value()) {
  347. if (result_arg_ids_[index.index].has_value() &&
  348. result_arg_ids_[index.index] != arg_const_inst_id) {
  349. if (diagnose_) {
  350. // TODO: Include the two different deduced values.
  351. CARBON_DIAGNOSTIC(DeductionInconsistent, Error,
  352. "inconsistent deductions for value of generic "
  353. "parameter `{0}`",
  354. SemIR::NameId);
  355. auto diag = context().emitter().Build(
  356. loc_id_, DeductionInconsistent, entity_name.name_id);
  357. NoteGenericHere(context(), generic_id_, diag);
  358. diag.Emit();
  359. }
  360. return false;
  361. }
  362. result_arg_ids_[index.index] = arg_const_inst_id;
  363. }
  364. continue;
  365. }
  366. case CARBON_KIND(SemIR::ValueParamPattern pattern): {
  367. Add(pattern.subpattern_id, arg_id);
  368. continue;
  369. }
  370. case SemIR::StructValue::Kind:
  371. // TODO: Match field name order between param and arg.
  372. break;
  373. case CARBON_KIND(SemIR::FacetAccessType access): {
  374. // Given `fn F[G:! Interface](g: G)`, the type of `g` is `G as type`.
  375. // `G` is a symbolic binding, whose type is a facet type, but `G as
  376. // type` converts into a `FacetAccessType`.
  377. //
  378. // When we see a `FacetAccessType` parameter here, we want to deduce the
  379. // facet type of `G`, not `G as type`, for the argument (so that the
  380. // argument would be a facet value, whose type is the same facet type of
  381. // `G`. So here we "undo" the `as type` operation that's built into the
  382. // `g` parameter's type.
  383. Add(access.facet_value_inst_id, arg_id);
  384. continue;
  385. }
  386. // TODO: Handle more cases.
  387. default:
  388. if (param_inst.kind().deduce_through()) {
  389. // Various kinds of parameter should match an argument of the same
  390. // form, if the operands all match.
  391. auto arg_inst = context().insts().Get(arg_id);
  392. if (arg_inst.kind() != param_inst.kind()) {
  393. break;
  394. }
  395. worklist_.AddInstArg(param_inst.arg0_and_kind(), arg_inst.arg0());
  396. worklist_.AddInstArg(param_inst.arg1_and_kind(), arg_inst.arg1());
  397. continue;
  398. }
  399. break;
  400. }
  401. // We didn't manage to deduce against the syntactic form of the parameter.
  402. // Convert it to a canonical constant value and try deducing against that.
  403. auto param_const_id = context().constant_values().Get(param_id);
  404. if (!param_const_id.has_value() || !param_const_id.is_symbolic()) {
  405. // It's not a symbolic constant. There's nothing here to deduce.
  406. continue;
  407. }
  408. auto param_const_inst_id =
  409. context().constant_values().GetInstId(param_const_id);
  410. if (param_const_inst_id != param_id) {
  411. Add(param_const_inst_id, arg_id);
  412. continue;
  413. }
  414. }
  415. return true;
  416. }
  417. // Gets the entity name of a generic binding. The generic binding may be an
  418. // imported instruction.
  419. static auto GetEntityNameForGenericBinding(Context& context,
  420. SemIR::InstId binding_id)
  421. -> SemIR::NameId {
  422. // If `binding_id` is imported (or referenced indirectly perhaps in the
  423. // future), it may not have an entity name. Get a canonical local instruction
  424. // from its constant value which does.
  425. binding_id = context.constant_values().GetConstantInstId(binding_id);
  426. if (auto bind_name =
  427. context.insts().TryGetAs<SemIR::AnyBindName>(binding_id)) {
  428. return context.entity_names().Get(bind_name->entity_name_id).name_id;
  429. } else {
  430. CARBON_FATAL("Instruction without entity name in generic binding position");
  431. }
  432. }
  433. auto DeductionContext::CheckDeductionIsComplete() -> bool {
  434. // Check we deduced an argument value for every parameter, and convert each
  435. // argument to match the final parameter type after substituting any deduced
  436. // types it depends on.
  437. for (auto&& [i, deduced_arg_id] :
  438. llvm::enumerate(llvm::MutableArrayRef(result_arg_ids_)
  439. .drop_front(first_deduced_index_.index))) {
  440. auto binding_index = first_deduced_index_.index + i;
  441. auto binding_id = context().inst_blocks().Get(
  442. context().generics().Get(generic_id_).bindings_id)[binding_index];
  443. if (!deduced_arg_id.has_value()) {
  444. if (diagnose_) {
  445. CARBON_DIAGNOSTIC(DeductionIncomplete, Error,
  446. "cannot deduce value for generic parameter `{0}`",
  447. SemIR::NameId);
  448. auto diag = context().emitter().Build(
  449. loc_id_, DeductionIncomplete,
  450. GetEntityNameForGenericBinding(context(), binding_id));
  451. NoteGenericHere(context(), generic_id_, diag);
  452. diag.Emit();
  453. }
  454. return false;
  455. }
  456. // If the binding is symbolic it can refer to other earlier bindings in the
  457. // same generic, or from an enclosing specific. Substitute to replace those
  458. // and get a non-symbolic type in order for us to know the final type that
  459. // the argument needs to be converted to.
  460. //
  461. // Note that when typechecking a checked generic, the arguments can
  462. // still be symbolic, so the substitution would also be symbolic. We are
  463. // unable to get the final type for symbolic bindings until deducing with
  464. // non-symbolic arguments.
  465. //
  466. // TODO: If arguments of different values, but that _convert to_ the same
  467. // value, are deduced for the same symbolic binding, then we will fail
  468. // typechecking in Deduce() with conflicting types via the
  469. // `DeductionInconsistent` diagnostic. If we defer that check until after
  470. // all conversions are done (after the code below) then we won't diagnose
  471. // that incorrectly.
  472. auto binding_type_id = context().insts().Get(binding_id).type_id();
  473. if (binding_type_id.is_symbolic()) {
  474. auto param_type_const_id =
  475. SubstConstant(context(), SemIR::LocId(binding_id),
  476. binding_type_id.AsConstantId(), substitutions_);
  477. CARBON_CHECK(param_type_const_id.has_value());
  478. binding_type_id =
  479. context().types().GetTypeIdForTypeConstantId(param_type_const_id);
  480. Diagnostics::AnnotationScope annotate_diagnostics(
  481. &context().emitter(), [&](auto& builder) {
  482. if (diagnose_) {
  483. NoteInitializingParam(binding_id, builder);
  484. }
  485. });
  486. auto converted_arg_id =
  487. diagnose_ ? ConvertToValueOfType(context(), loc_id_, deduced_arg_id,
  488. binding_type_id)
  489. : TryConvertToValueOfType(context(), loc_id_,
  490. deduced_arg_id, binding_type_id);
  491. // Replace the deduced arg with its value converted to the parameter
  492. // type. The conversion of the argument type must produce a constant value
  493. // to be used in deduction.
  494. if (auto const_inst_id =
  495. context().constant_values().GetConstantInstId(converted_arg_id);
  496. const_inst_id.has_value()) {
  497. deduced_arg_id = const_inst_id;
  498. } else {
  499. if (diagnose_) {
  500. CARBON_DIAGNOSTIC(RuntimeConversionDuringCompTimeDeduction, Error,
  501. "compile-time value requires runtime conversion, "
  502. "constructing value of type {0}",
  503. SemIR::TypeId);
  504. auto diag = context().emitter().Build(
  505. loc_id_, RuntimeConversionDuringCompTimeDeduction,
  506. binding_type_id);
  507. NoteGenericHere(context(), generic_id_, diag);
  508. diag.Emit();
  509. }
  510. deduced_arg_id = SemIR::ErrorInst::InstId;
  511. }
  512. }
  513. substitutions_.push_back(
  514. {.bind_id = SemIR::CompileTimeBindIndex(binding_index),
  515. .replacement_id = context().constant_values().Get(deduced_arg_id)});
  516. }
  517. return true;
  518. }
  519. auto DeductionContext::MakeSpecific() -> SemIR::SpecificId {
  520. // TODO: Convert the deduced values to the types of the bindings.
  521. return Check::MakeSpecific(context(), loc_id_, generic_id_, result_arg_ids_);
  522. }
  523. auto DeduceGenericCallArguments(
  524. Context& context, SemIR::LocId loc_id, SemIR::GenericId generic_id,
  525. SemIR::SpecificId enclosing_specific_id, SemIR::InstId self_type_id,
  526. [[maybe_unused]] SemIR::InstBlockId implicit_param_patterns_id,
  527. SemIR::InstBlockId param_patterns_id,
  528. [[maybe_unused]] SemIR::InstId self_id,
  529. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::SpecificId {
  530. DeductionContext deduction(&context, loc_id, generic_id,
  531. enclosing_specific_id, self_type_id,
  532. /*diagnose=*/true);
  533. // Prepare to perform deduction of the explicit parameters against their
  534. // arguments.
  535. // TODO: Also perform deduction for type of self.
  536. deduction.AddAll(param_patterns_id, arg_ids);
  537. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  538. return SemIR::SpecificId::None;
  539. }
  540. return deduction.MakeSpecific();
  541. }
  542. auto DeduceImplArguments(Context& context, SemIR::LocId loc_id,
  543. const SemIR::Impl& impl, SemIR::ConstantId self_id,
  544. SemIR::SpecificId constraint_specific_id)
  545. -> SemIR::SpecificId {
  546. DeductionContext deduction(&context, loc_id, impl.generic_id,
  547. /*enclosing_specific_id=*/SemIR::SpecificId::None,
  548. /*self_type_id=*/SemIR::InstId::None,
  549. /*diagnose=*/false);
  550. // Prepare to perform deduction of the type and interface.
  551. deduction.Add(impl.self_id, context.constant_values().GetInstId(self_id));
  552. deduction.Add(impl.interface.specific_id, constraint_specific_id);
  553. if (!deduction.Deduce() || !deduction.CheckDeductionIsComplete()) {
  554. return SemIR::SpecificId::None;
  555. }
  556. return deduction.MakeSpecific();
  557. }
  558. } // namespace Carbon::Check