deduce.cpp 28 KB

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