deduce.cpp 26 KB

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