deduce.cpp 26 KB

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